PHP Classes

Slugify Models: Create a URL slug for a Laravel model class

Recommend this page to a friend!
  Info   View files Example   View files View files (3)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not yet rated by the usersTotal: 19 All time: 11,247 This week: 673Up
Version License PHP version Categories
slugify_model 1.0GNU General Publi...7.4HTTP, Blogs, PHP 7, Global


This package can create a URL slug for a Laravel model class.

It provides a helper function that takes as parameters a Laravel model class object or a string and the name of the model title column.

The function computes a slug string that can be used as part of the URL to generate a human-readable URL for pages that show views of model class object information.

Save 'slugify_model.php' in your 'app/Helpers/' directory and update your composer.json to reference and autoload the helper function.

Picture of Shashwat Mishra
Name: Shashwat Mishra <contact>
Classes: 3 packages by
Country: India India
Age: 27
All time rank: 4275295 in India India
Week rank: 262 Up17 in India India Up
Innovation award
Innovation award
Nominee: 1x



/* Usage Example: Post */

$validated = $request->validated();

// Creating a New Model
$validated['slug'] = slugify_model(Post::class, $validated['title']);
// return: this-is-an-example-of-slugify
// if slug already exists: this-is-an-example-of-slugify-9rkt6


// Updating a Model
$validated['slug'] = slugify_model(
model: Post::class,
columnOrTitle: $validated['title'],
ignore: $post->slug
// return: this-is-an-updated-example-of-slugify
// if slug already exists: this-is-an-updated-example-of-slugify-jToVK

// On-the-fly Slugify :P

// 1. Here, 'title' Column in 'posts' table will be slugified
// and 'slug' column will be used to verify if it exists.
$slug = slugify_model($post, 'title');
// return: on-the-fly-slugify

// 2. Here, custom slug column is used to verify if it exists.
$slug = slugify_model($post, 'title', slugColumn: 'shortname');
// return: on-the-fly-slugify

// 3. Ignoring a Slug when ClassName::class is provided as first param
$slug = slugify_model(Post::class, $validated['title'], $post->slug);

  Files folder image Files  
File Role Description
Plain text file examples.php Example Examples to Use the function.
Plain text file composer.json Doc. This shows how to autoload the helper function in laravel.
Plain text file slugify_model.php Class Helper Function

 Version Control Unique User Downloads Download Rankings  
This week:0
All time:11,247
This week:673Up