PHP Classes

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

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

Author

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
Innovation award
Innovation award
Nominee: 1x

Example

<?php

/* 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

Post::create($validated);


// 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
$post->update($validated);



// 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 (3)  
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

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 0%
Total:19
This week:0
All time:11,370
This week:673Up