Create a slug from a string Lavavel 8
Graham Morby

Graham Morby @grahammorby

About: Hey guys, 15-year developer! I code with Vue.js and Python, I love to learn but also love to teach! So I try and write informative tutorials and posts. I am new to blogging and would love any feedback

Location:
Portsmouth UK
Joined:
Dec 9, 2019

Create a slug from a string Lavavel 8

Publish Date: Jan 6 '21
18 4

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!

Comments 4 total

  • Bunyamin Kurt
    Bunyamin KurtJan 9, 2021

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

    • Graham Morby
      Graham MorbyJan 10, 2021

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

  • Hendrik
    HendrikJun 11, 2021

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

Add comment