DEV Community

Morcos Gad
Morcos Gad

Posted on

How to Create Custom Slug using Title in Laravel

Let's get started quickly and create a Slug with today's date

$slug = Str::slug('Hello Word');
$slug .= '-';
$slug .= \Carbon\Carbon::parse(now())->format('m-d-Y');
return $slug; //hello-word-11-13-2021
Enter fullscreen mode Exit fullscreen mode

Now let's see how to use it better

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;
  })()
]);
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code.

Top comments (0)