Generating a URL friendly slug using a given separator:
$slug = Str::slug('My Page Title', '_');
Please help me to generate a Unique Slug From Title
Generating a URL friendly slug using a given separator:
$slug = Str::slug('My Page Title', '_');
You can use the Str class shipped with laravel:
Str::slug($request->get('title'));
Or you can use this great package. https://github.com/cviebrock/eloquent-sluggable which has exactly what you're looking for.
I Tried this method. but im getting this Error
FatalErrorException in PageController.php line 63: Class 'Str' not found
Try this then:
$slug = \Str::slug('My Page Title', '_');
It depends where it's called from with regards to namespacing.
@sitesense Thanks for Replay .. This also i tried . again im getting the same Error :(
Hello @Bribin, here I tried my own solution, and it works well:
And if you want to improve it, you can use what @blomdahldaniel say here:
Good luck!
@bribin ah you might want to add this to your aliases array in config/app.php:
'Str' => 'Illuminate\Support\Str',
The best solution from the man himself @JeffreyWay
https://laracasts.com/discuss/channels/general-discussion/l5-routing-1
I use this method on my Model - a slug is automatically generated each time the model is saved.
public static function boot()
{
parent::boot();
static::saving(function($model) {
$model->slug = str_slug($model->title);
return true;
});
}
What happens here when you do something like (on a create method):
$slug = str_slug($project); .
And you try to enter a project by the same name.
Will it throw errors, or will it just make a slug with an identifier (ex:project-2) at the end?
PS: slug is set to unique in model/migration
I was trying this lesson https://laracasts.com/lessons/unique-slugs-in-laravel To make it work change this
static::whereRaw("slug REGEXP '^{$model->slug}(-[0-9]*)?$'")
To
static::whereRaw("slug = '$model->slug' or slug LIKE '$model->slug-%'")
Complete code put this on you're model
public static function boot()
{
parent::boot();
static::creating(function($model) {
$model->slug = str_slug($model->ToBeSluggified);// change the ToBeSluggiefied
$latestSlug =
static::whereRaw("slug = '$model->slug' or slug LIKE '$model->slug-%'")
->latest('id')
->value('slug');
if ($latestSlug) {
$pieces = explode('-', $latestSlug);
$number = intval(end($pieces));
$model->slug .= '-' . ($number + 1);
}
});
}
Laravel 5.6
use Illuminate\Support\Str;
$slug = Str::slug('My Page Title', '_');
it work for me
Please or to participate in this conversation.