Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Laravel slug generator using trait

Laravel reusable slug generator using trait

Aman Jain, November 8, 2021November 8, 2021

In our last article Laravel slug generator with example we demonstrate how we can generate slug for model but in that article we need to rewrite the same code for multiple models if we want use the slug generation in multiple model. so in this article i will show you how can we achieve a reusable slug generator in laravel.we are going to create slug from any input field. slug is useful search engine optimization and also from security perspective because in some case we use primary id or unique id of table to fetch the detail in page but its not recommended way to show number in URL. Showing ID in URL can be open to SQL injection which lead to website hacking.

Create reusable slug using trait

In this way we will create a event in every model to generate the slug and save into the table.

Step 1: Create a model

First step is to create the model using artisan command or you can choose your any model

php artisan make:model Post

it will generate a Post model in app\Model folder.

Step 2: Create a trait and register events

Now, we need to create a trait in folder app\Traits and file Sluggable.php. if Traits folder already in app folder then you can directly copy the file and paste in Sluggable.php

<?php

namespace App\Traits;

use Illuminate\Support\Str;

trait Sluggable
{
    private static $__sluggableConfig=["slug_column"=>"slug","slug_from_column"=>"title"];

    protected static function bootSluggable()
    {
        
        self::setSluggableConfig();  // set initial config for sluggable

        static::creating(function ($model) {
           
            $model->{self::$__sluggableConfig['slug_column']} = $model->generateUniqueSlug($model->{self::$__sluggableConfig['slug_from_column']},0,self::$__sluggableConfig['slug_column']);
            
        });
      

    }

    private static function setSluggableConfig(){ 
        
           
            if(isset(self::$sluggableConfig['slug_column'])){
                self::$__sluggableConfig['slug_column']=self::$sluggableConfig['slug_column'];
            }
            else{
                self::$__sluggableConfig['slug_column']="slug";
            } 

            if(isset(self::$sluggableConfig['slug_from_column'])){
                self::$__sluggableConfig['slug_from_column']=self::$sluggableConfig['slug_from_column'];
            }
            else{
                self::$__sluggableConfig['slug_from_column']="title";
            } 
    

    }
    private function generateUniqueSlug($name,$counter=0,$slugField="slug")
    {
        $updatedName = $counter==0?$name:$name."-".$counter;
        if (static::where($slugField,Str::slug($updatedName))->exists()) {
               return  $this->generateUniqueSlug($name,$counter+1);
        }
        return Str::slug($updatedName);
    }   
}

Here , we created a boot method bootSluggable and then registered a event static::creating to catch the creating event from model.

Then, we are also setting some basic settings for this plugin using setSluggableConfig to set the slug column and set the slug from column(slug_from_column).

After it we created a dynamic method generateUniqueSlug to generate the unique slug for each row of table.

Step 4: Add trait to model

We have successfully created a trait and now its time to use it in our any model, here we will use it in our created post model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Post extends Model
{
    use HasFactory;
    use \App\Traits\Sluggable;
    
}

In above code we used use \App\Traits\Sluggable; to implement the slug feature in model.

By default this trait use slug column for slug and generator column title. we can also change this behavior by defining a property $sluggableConfig which accepts a array.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Post extends Model
{
    use HasFactory;
    use \App\Traits\Sluggable;
    private static $sluggableConfig=["slug_column"=>"slug","slug_from_column"=>"title"];
    
}

Step 3: Create the route and save post

This is the time to check our implementation, so we need to create the route and create a new post

<?php

use Illuminate\Support\Facades\Route;
use App\Models\Post;


Route::get('/check-slug',function(){

    $post=new Post;
    $post->title="This is a test";
    $post->description="This is a test";
    $post->save();
});

now we can check in browser and below is screenshot

Screenshot 2021 11 07 at 6.45.18 PM
Slug generation in laravel

Related

Php Laravel laravelphpslugtraits

Post navigation

Previous post
Next post

Related Posts

Php html string in blade in laravel

How to Render Html String in Blade in Laravel ?

March 8, 2022December 2, 2023

Blade is a template engine to write the syntax easily and powerfully. To render html string in blade in laravel we use {!! $htmlstring !!}. Using the blade template we can easily print a variable, can create loops and can create directives and components too. Laravel blade template uses filename.blade.php…

Read More
Laravel get single column value in laravel

How to get single column value in laravel ?

November 14, 2023March 16, 2024

In this guide, we’ll dive into get single column value in Laravel Eloquent ORM. In Laravel development, optimizing database queries is pivotal for creating efficient and high-performance applications. This technique is valuable for extracting targeted data from your database, enhancing the precision and speed of your application. To illustrate get…

Read More
Php Unique Validation in laravel 8

Unique validation on Update in Laravel with example

June 19, 2022November 17, 2023

In this article we will learn to handle the unique validation on update in laravel.As we know Laravel support validation for database operations. Laravel unique validation validates the table column uniqueness using unique validation. In this tutorial we will learn about the unique validation to table columns and also while…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version