DEV Community

Cover image for Laravel Route Parameters: How to retrieve and use them
Bilal Haidar
Bilal Haidar

Posted on

Laravel Route Parameters: How to retrieve and use them

In PHP Laravel, you can retrieve route parameters in several ways and in different places. Below, I'll provide you with code examples for each method:

  • Using the Route Facade: You can use the Route facade to access route parameters. Here's an example:
   $parameter = Route::current()->parameter('parameterName');
Enter fullscreen mode Exit fullscreen mode
  • Using the request Object: You can also retrieve route parameters using the request object's route() method:
   $parameter = request()->route('parameterName');
Enter fullscreen mode Exit fullscreen mode
  • Using Route Model Binding: If you have defined route model binding in your routes or controllers, Laravel will automatically retrieve the model instance associated with the parameter. For example:
   public function show(User $user) {
       // $user is an instance of the User model
   }
Enter fullscreen mode Exit fullscreen mode
  • Using the Route::input() Method: This method allows you to access route parameters directly:
   $parameter = Route::input('parameterName');
Enter fullscreen mode Exit fullscreen mode
  • Using Type-Hinting in Controller Methods: You can type-hint parameters in controller methods, and Laravel will automatically resolve them:
   public function show($parameterName) {
       // Laravel resolves $parameterName from the route parameter
   }
Enter fullscreen mode Exit fullscreen mode
  • Using the request() Helper Function: You can also use the request() helper function to retrieve route parameters:
   $parameter = request('parameterName');
Enter fullscreen mode Exit fullscreen mode
  • Using the $request Object direct parameter access: You can also use the $request->parameterName directly to retrieve route parameters:
   $parameter = $request->parameterName;
Enter fullscreen mode Exit fullscreen mode

These are various ways to retrieve route parameters in Laravel, and you can choose the one that best fits your specific use case.

Top comments (1)

Collapse
 
devnbeyond profile image
DevNbeyond

I wish you could elaborate more on this, and the use cases of each one of them. as a beginner i found this article a bit difficult to grasp