This tutorial is part of the Laravel Handbook. Download it from https://flaviocopes.com/access/
In Laravel, creating static routes in the routes/web.php
file is a common practice. However, there might be scenarios where you need to generate dynamic routes based on database content. This is where dynamic routes come in handy.
Let’s say you want to create a page for each individual dog in your database, with specific details and images. Instead of creating separate static routes for each dog, you can use dynamic routes to achieve the desired functionality.
Here’s an example of a static route in Laravel:
Route::get('/dogs', function () {
return view('dogs');
})->name('dogs');
To create dynamic routes for each dog, you can use a dynamic segment in the URL, denoted by {slug}
. For instance:
Route::get('/dogs/{slug}', function ($slug) {
return view('dog', ['slug' => $slug]);
});
In this example, the $slug
variable represents the unique identifier for each dog. The slug is typically a lowercase, space-less string derived from the dog’s name.
To retrieve the actual dog data from the database, you can utilize the Dog
model within the route. Consider the following code snippet:
use App\Models\Dog;
Route::get('/dogs/{slug}', function ($slug) {
$dog = Dog::find($slug);
return view('dog', ['dog' => $dog]);
});
By using the Dog
model, you can fetch the corresponding dog record based on the provided slug. This allows you to pass the retrieved data to the view and display it accordingly.
Using dynamic routes not only simplifies your code but also helps to create SEO-friendly URLs. Instead of generating numerous static routes, you can dynamically generate URLs based on the database content, improving the discoverability and search engine optimization of your application.
Tags: dynamic routes, Laravel, slug, SEO-friendly URLs, database