Dynamic routes in Laravel
We’ve seen how to create a route in the routes/web.php file:
Route::get('/dogs', function () {
return view('dogs');
})->name('dogs');
This is a static route, that responds on the /dogs URL.
Now suppose you want to create a page for each single dog, maybe you’ll fill that with a description, an image, whatever.
You can’t create a static route for each dog in the database, because you don’t know the name of the dog.
Imagine you have 2 dogs Max and Daisy, this would display a “dog” view (which we don’t have yet) on the /dogs/max and /dogs/daisy:
Route::get('/dogs/max', function () {
return view('dog');
})
Route::get('/dogs/daisy', function () {
return view('dog');
})
What we do instead is, we have a dynamic segment in the URL:
Route::get('/dogs/{slug}', function () {
return view('dog');
})
slug is a term that identifies a URL portion in lowercase and without spaces, for example if the name of the dog is Max, the slug is
max.
Now we can pass the slug value to the callback function (the function that’s called when the route is hit), and inside the function we can pass it to the view:
Route::get('/dogs/{slug}', function ($slug) {
return view('dog', ['slug' => $slug]);
})
Now the $slug variable is available inside the Blade template.
But we want to retrieve the actual dog data. We have the slug, which we can imagine it’s stored in the database when we add the dog.
To do that, we use the Dog model in the route, like this:
use App\Models\Dog;
Route::get('/dogs/{slug}', function ($slug) {
$dog = Dog::find($slug)
return view('dog', ['dog' => $dog]);
}) download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.