📜  在创建 laravel 时生成 slug - PHP 代码示例

📅  最后修改于: 2022-03-11 14:53:44.891000             🧑  作者: Mango

代码示例1
/**
 * Laravel provides a boot method which is 'a convenient place to 
 * register your event bindings.'
 * See: https://laravel.com/docs/master/eloquent#events
 */
public static function boot()
{
    parent::boot();

    // registering a callback to be executed upon the creation of an activity AR
    static::creating(function($activity) {

        // produce a slug based on the activity title
        $slug = \Str::slug($news->title);

        // check to see if any other slugs exist that are the same & count them
        $count = static::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();

        // if other slugs exist that are the same, append the count to the slug
        $activity->slug = $count ? "{$slug}-{$count}" : $slug;

    });

}
// Use the create method
Activity::create(['title'=>'lorem ipsum']);