How to deal easy with Slugs in Laravel

Slugs are important part of the SEO of any website, so here is a little snippet method that can be used in the Model to retrieve a longer slugs that contain some relationships, without messing the view files with unneeded code.


Lets say we have an Article, that contains Multiple Categories, in that case, if we want to have a category in the url slug of the article, we also need to have maincategory() relationship, so we know which category is the main one ( aka used in the url slug )


Simply add this code in your App\Article.php model, and then whenever you need to retrieve the url of an article, you can use

$article->urlslug() , which will generate an url.


public function urlslug() {
$slug = url('articles/'.$this->id . '/'. $this->maincategory->slug . '/' . $this->slug);

return $slug;