📅  最后修改于: 2023-12-03 15:32:33.815000             🧑  作者: Mango
In Laravel, a slug is a URL-friendly version of a string, typically used to create cleaner, more readable URLs for resources. The str_slug
function in Laravel generates a slug from a given string.
For example, if the title of a blog post is "How to Use Laravel to Create Slugs", the slug generated by the str_slug
function would be "how-to-use-laravel-to-create-slugs".
In this tutorial, we will learn how to generate slugs in Laravel using the str_slug
function.
Laravel comes with the str_slug
function out of the box, so there's no need to install anything.
To generate a slug from a given string in Laravel, simply use the str_slug
function like this:
use Illuminate\Support\Str;
$slug = Str::slug('How to Use Laravel to Create Slugs');
The str_slug
function will generate a slug that is URL-friendly and can be used in the URL of the resource.
The str_slug
function also has some additional options that can be used to customize the generation of slugs.
By default, the str_slug
function uses a hyphen (-) as the separator between words in the string. If you want to use a different separator, you can pass it as a second argument to the function like this:
$slug = Str::slug('How to Use Laravel to Create Slugs', '_');
This will generate a slug with underscores (_) instead of hyphens.
The str_slug
function also supports different languages when generating a slug. By default, it uses the English language. If you want to use a different language, you can pass it as a third argument to the function like this:
$slug = Str::slug('Cómo Utilizar Laravel para Crear Slugs', '-', 'es');
This will generate a slug in Spanish with hyphens (-) as the separator.
The str_slug
function in Laravel is a powerful tool for generating slugs from any given string. By default, it is easy to use, but it also has some additional customization options that can be useful in certain situations. With this knowledge, you can now create cleaner, more readable URLs for your resources in Laravel.