Automatically generate slug when saving model.

(220 hits) 13 Dec 2018 in Web Development by Dario Mindoro


This snippet code automatically generate a url-friendly slug where spaces are converted into dash character for website address, normally use in some blog page of the website

class Item extends Model
{
public static function boot()
{
parent::boot();
static::saving(function ($model) {
$model->slug = str_slug($model->name);
});
}
}
Slug is a Laravel helper that converts a given string into a dash separated string

str_slug()

The str_slug function generates a URL friendly "slug" from the given string:

$title = str_slug('Laravel 5 Framework', '-');


Tagged in : Laravel, Php, JavaScript

avatar
Author :
Dario Mindoro

Author of Mindworksoft.com, Full-stack developer, interested in media streaming, automation, photography, AI, and digital electronics