📅  最后修改于: 2023-12-03 15:02:35.500000             🧑  作者: Mango
When building a website, you often want to create "pretty" URLs that are easy to read and remember. One way to do this in Laravel is by using "slugs" in your routes.
A slug is a URL-friendly version of a string that is usually used to identify a resource. For example, if you have a blog post titled "My First Blog Post," you might use the slug "my-first-blog-post" in the URL.
In Laravel, you can define a route with a slug parameter like this:
Route::get('posts/{slug}', 'PostsController@show');
In this example, the {slug}
parameter will match any string in the URL and pass it to the show
method of the PostsController
.
To generate a slug from a string in Laravel, you can use the Str::slug
method like this:
$slug = \Illuminate\Support\Str::slug('My First Blog Post');
// Result: my-first-blog-post
You can also customize the separator used in the slug by passing a second argument to the Str::slug
method:
$slug = \Illuminate\Support\Str::slug('My First Blog Post', '_');
// Result: my_first_blog_post
One thing to keep in mind when using slugs in your routes is that they should be unique for each resource. If you have two blog posts with the same title, you should use a different slug for each one.
Overall, using slugs in your Laravel routes can make your URLs more readable and SEO-friendly. Just remember to keep them unique and use a consistent format.