Search

How To Create Slug in Larave ?

  • Share this:
post-title

Why do we need slug?

Slug is just a simplified string that comes at the end of URL which usually refers to some specific page or post. It makes your URL SEO and user friendly. Slugs can also improve your ranking in the search engine as it makes it easy to predict the content of the page.

If you have worked with laravel then, normally you would refer each post via id.

https://example.com/post/1

These URLs are definitely not user friendly. Instead, we can use some value like your post title to convert into slug using Str::slug() and you can get URLs like this.

https://example.com/post/sample-post

Create Slug using Illuminate\Support\Str helper;

public function store(Request $request)
{
    $request->validate([
        'name' => 'required|string|max:255',
        'slug' => 'required|string|max:255',
    ]);

    Post::create([
        'name' => $request->name,
        'slug' => \Str::slug($request->slug)
    ]);

    return redirect()->route('post.index');
}

Create direct slug in name place. using 'slug' => \Str::slug($request->name);

public function store(Request $request)
{
    $request->validate([
        'name' => 'required|string|max:255',
    ]);

    Post::create([
        'name' => $request->name,
        'slug' => \Str::slug($request->name)
    ]);

    return redirect()->route('post.index');
}

You can create slug using str()->slug('laravel > 9') helper method. laravel > 9 support str(), so you do not need to import any class you can access str() anywhere.

public function store(Request $request)
{
    $request->validate([
        'name' => 'required|string|max:255',
        'slug' => 'required|string|max:255',
    ]);

    Post::create([
        'name' => $request->name,
        'slug' => str()->slug($request->slug)

    ]);

    return redirect()->route('post.index');
}
About author
Here’s My little description of your attention on Me and My blog. I am here to help you with PHP programming.
View all posts (51)