How to Create Custom Slug using Title in Laravel

Hello Artisan hope you are doing very well. In this tutorial i will discuss about laravel slug. In this laravel slug tutorial i will show you how you can create your own custom slug. That we will generate slug from title first then we will make it custom by adding extra attributes like date, author name etc.

If you don't know how to generate slug before save in Laravel then this article is perfect for you. Sometimes we will face some error like call to undefined function apphttpcontrollersstr slug before going to create slug.

In this example you will learn how to solve it and how to create unique slug in laravel also. Let's see use slug instead of id how we can do that.

Example code : 

Page::create([
  'title' => $request->title,
  'body'  => $request->body,
  'published_at' => $request->published_at,
  'slug' => (function(){
        $slug = \Str::slug($request->title);
        $slug .= '-';
        $slug .= \Carbon\Carbon::parse($request->published_at)->format('m-d-Y');
        return $slug;
  })()
]);

 

Recommended : Laravel Working With Json Table Column Example

 

Now just customize this code like what ever you want. Hope it will help you to make custom slug.