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!