How to create dynamic route in laravel?


by dedrick , in category: PHP General , 6 months ago

How to create dynamic route in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 6 months ago


To create a dynamic route in Laravel, follow these steps:

  1. Open the routes/web.php file in your Laravel project.
  2. Define a route using the Route::get() method. For example, Route::get('/user/{id}', 'UserController@show').
  3. In the route definition, use curly braces {} to indicate a dynamic route parameter. In this example, we're using {id} as the dynamic parameter.
  4. Specify the controller and method that should handle the route. In this example, UserController is the controller and show is the method.
  5. In the corresponding controller method (in this case, show method in UserController), use the $id parameter to retrieve the dynamic value and perform any necessary actions.
  6. You can define additional dynamic parameters by separating them with slashes. For example, Route::get('/user/{id}/post/{postId}', 'UserController@showPost').

That's it! Now you have a dynamic route that can accept different values for the specified parameter (e.g., /user/1, /user/2, etc.).