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

Laravel slug generator with example

Aman Jain, November 8, 2021November 8, 2021

In this article 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.

There is 3 ways to create the slug in Laravel

  1. Create save event in model
  2. Slug using trait
  3. Slug using package

Create slug using save event

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: Register the create event

Now, register a createed event on every new row creation

<?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;

    protected static function boot()
    {
        parent::boot();

        static::created(function ($post) {
            $post->slug = $post->generateUniqueSlug($post->title);
            $post->save();
        });
    }

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

Here , we registered a event static::created and then generated a unique slug by checking the existancy of slug recursively in database.

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
Read about Create a reusable slug using trait

Related

Php Laravel laravelphpslug

Post navigation

Previous post
Next post

Related Posts

Php How to Store Array in Database Laravel

How to Store Array in Database Laravel ?

July 29, 2022March 16, 2024

In this article we will learn to Store Array in Database Laravel. Sometime in our application we have some raw information which we only want to store in our database and later on wanted to show back again. These type of information or data is only used for to keep…

Read More
Php Laravel avg in eloquent query

How to use avg in Laravel eloquent query with example

January 30, 2022January 30, 2022

In this article we will learn to use aggregate function avg in laravel eloquent and query builder. Laravel itself provide inbuilt method to avg the columns like in MySQL or SQL based database we can do avg of columns using avg aggregate function. Avg method will give you the average…

Read More
Php How to get random rows in laravel example

How to get random rows in laravel example ?

October 10, 2022March 16, 2024

In this blog post, we’ll take a look at how to get random rows in Laravel database. We’ll explore the use of the QueryBuilder, Eloquent, and the DB facade. laravel has inbuilt eloquent method to get the random records from database using the inRandomOrder method. we will understand the random…

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