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);
}
The line you want to concentrate on is
$article->slug = Str::slug($request->input('title'), "-");
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;
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)
This is cool. I was using my own slugify function for old version of laravel.
This is better.
It's pretty awesome right!? I found it so much easier than the old way - super glad it helped
How would I make it so that it adds a -1 and -2 behind the slug when there is a duplicate
concatenate with id.