How to get value of URL parameters into Controller (Laravel)

How to get value of URL parameters into Controller (Laravel)

Passing Parameters in Laravel Routes

When working with Laravel, you’ll often need to pass data through URLs. Laravel provides two main ways to do this: query parameters and URL segments. Here's how both methods work:

1. Using Query Parameters (After ?)

URL Example:

http://www.yoursite.com/controllerMethod?key=value

Route Definition:

Route::get('controllerMethod', [YourController::class, 'controllerMethod']); // Or in older Laravel syntax: // Route::get('controllerMethod', 'YourController@controllerMethod');

Controller Method:

use Illuminate\Http\Request; public function controllerMethod(Request $request) { $key = $request->key; // or $request->input('key'); echo $key; }

Use query parameters when the value is optional, or when you're applying filters or search criteria.

2. Using URL Segment Parameters (Without ?)

URL Example:

http://www.yoursite.com/controllerMethod/value

Route Definition:

Route::get('controllerMethod/{key}', [YourController::class, 'controllerMethod']);

Controller Method:

public function controllerMethod($key) { echo $key; }

Use URL segments for required route values such as IDs, slugs, or anything that should be part of the route structure.

Final Tip

Both methods are essential tools in Laravel routing:

  • Query Parameters — best for optional filters or inputs (?search=term)

  • URL Segments — ideal for defining structured, RESTful routes (/user/42)

Souy Soeng

Souy Soeng

Hi there šŸ‘‹, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
šŸ‘Æ I’m looking to collaborate on open-source PHP & JavaScript projects
šŸ’¬ Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
close