autogenerate slug for model laravel

Solutions on MaxInterview for autogenerate slug for model laravel by the best coders in the world

showing results for - "autogenerate slug for model laravel"
Lola
08 Jul 2016
1/**
2 * Laravel provides a boot method which is 'a convenient place to 
3 * register your event bindings.'
4 * See: https://laravel.com/docs/master/eloquent#events
5 */
6public static function boot()
7{
8    parent::boot();
9
10    // registering a callback to be executed upon the creation of an activity AR
11    static::creating(function($activity) {
12
13        // produce a slug based on the activity title
14        $slug = \Str::slug($news->title);
15
16        // check to see if any other slugs exist that are the same & count them
17        $count = static::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();
18
19        // if other slugs exist that are the same, append the count to the slug
20        $activity->slug = $count ? "{$slug}-{$count}" : $slug;
21
22    });
23
24}
25// Use the create method
26Activity::create(['title'=>'lorem ipsum']);
27
28