DEV Community

Cover image for Create a slug from a string Lavavel 8
Graham Morby
Graham Morby

Posted on • Updated on

Create a slug from a string Lavavel 8

So as normal I blog on topics I had to research and then pop them here for my reference and if you are reading this then its fantastic!

So I wanted to create a slug from a string in laravel and it was quite easy to do actually. So here we go.

We have a simple blog controller taking some request objects.

public function put(Request $request) {

        $article = new Blog;
        $article->title   = $request->input('title');
        $article->article = $request->input('article');
        $article->slug    = Str::slug($request->input('title'), "-");



        $article->save();

        $data = [
            'status' => 200,
            'data'   => 'Blog post created successfully'
        ];

        return response($data);

    }
Enter fullscreen mode Exit fullscreen mode

The line you want to concentrate on is

$article->slug    = Str::slug($request->input('title'), "-");
Enter fullscreen mode Exit fullscreen mode

This line uses a laravel helper function to take a string value and turn it to full lower case, and then add a - where a space exists. You can change that to be anything you wish.

At the top of our controller if you add

use Illuminate\Support\Str;
Enter fullscreen mode Exit fullscreen mode

That will pull in the required file that the helper function uses and should work like a dream.

Its as easy as that! Simple fast and slugging along!

Top comments (4)

Collapse
 
bjwlf profile image
Bunyamin Kurt

This is cool. I was using my own slugify function for old version of laravel.
This is better.

Collapse
 
grahammorby profile image
Graham Morby

It's pretty awesome right!? I found it so much easier than the old way - super glad it helped

Collapse
 
23chromosomes profile image
Hendrik

How would I make it so that it adds a -1 and -2 behind the slug when there is a duplicate

Collapse
 
sarozpradhan64 profile image
Saroj Pradhan

concatenate with id.