Laravel 9 Generate Unique Slug Generate Example

Laravel 9 generate unique slug Example; In this tutorial you will learn how to create dynamically unique slug or seo friendly slug URL before saving to database in laravel application using cviebrock/eloquent-sluggable package.

A slug is the url or human-readable unique identifier helps in finding a web page or web resource. A specific keyword or id denotes the slug. Not just Laravel 9 or 8, but you can use this unique guide to implement slug feature in the previous versions of laravel using the profound eloquent approach.

Create Unique Slug in Laravel

Use to Follow the following steps to create unique slug in laravel application:

  • Step 1: Download Laravel App
  • Step 2: Connect App to Database
  • Step 3: Install Eloquent Sluggable Package
  • Step 4: Build Model and Migration
  • Step 5: Build Routes
  • Step 6: Create Controller
  • Step 7: Create Blade View
  • Step 8: Start Your Application

Download Laravel App

In the beginning, open a terminal window and use the suggested command to create a fresh laravel application:

composer create-project --prefer-dist laravel/laravel laravel-unique-slug

Go into the app:

cd laravel-unique-slug

Connect App to Database

Next, insert database details in .env config file, it makes the laravel connection with the database:

DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306 
DB_DATABASE=here database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

Install Eloquent Sluggable Package

Now execute the following command on terminal install the eloquent sluggable package for generating unique slug:

composer require cviebrock/eloquent-sluggable

After successfully install eloquent sluggable package, type the below given command in command prompt:

php artisan vendor:publish --provider="Cviebrock\EloquentSluggable\ServiceProvider"

Generate Model and Migration

In this step, execute the following command on terminal to create model and migration file:

php artisan make:model Post -m

Get inside the database/migration/create_posts_table.php file, add the given below properties migration file.

<?php 
   
use Illuminate\Support\Facades\Schema; 
use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 
    
class CreatePostsTable extends Migration 
{ 
    /** 
     * Run the migrations. 
     * 
     * @return void 
     */
    public function up() 
    { 
        Schema::create('posts', function (Blueprint $table) { 
            $table->increments('id'); 
            $table->string('title'); 
            $table->string('slug'); 
            $table->text('description'); 
            $table->timestamps(); 
        }); 
    } 
    
    /** 
     * Reverse the migrations. 
     * 
     * @return void 
     */
    public function down() 
    { 
        Schema::dropIfExists('posts'); 
    } 
} 

Next, migrate the table using the below command:

php artisan migrate

Additionally, open app/Models/Post.php file and register the social login properties in here as well.

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    use HasFactory;
 
     protected $fillable = [
     'title',
     'slug',
     'description',
    ];
    public function sluggable()
    {
        return [
            'slug' => [
                'source' => 'title'
            ]
        ];
    }
}

Make Routes

Next, get into the routes/web.php file, and add the following routes to web.php file:

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
 
Route::resource('posts', PostController::class);

Create Controller

Now, generate a controller using the following command, this new controller will hold the generate unique slug programming logic.

php artisan make:controller PostController --resource

Plus, open app/Http/Controllers/PostController.php file and place the following code.

<?php
   
namespace App\Http\Controllers;
   
use App\Models\Post;
 
use Illuminate\Http\Request;
 
use Redirect;
 
use Cviebrock\EloquentSluggable\Services\SlugService;
   
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['post'] = Post::orderBy('id','desc')->paginate(10);
   
        return view('post.list',$data);
    }
    
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('post.create');
    }
   
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'description' => 'required',
        ]);
 
        $insert = [
            'slug' => SlugService::createSlug(Post::class, 'slug', $request->title),
            'title' => $request->title,
            'description' => $request->description,
        ];
   
        Post::insertGetId($insert);
    
        return Redirect::to('posts')
       ->with('success','Greate! posts created successfully.');
    }
    
    /**
     * Display the specified resource.
     *
     * @param  \App\Post $post
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
         
    }
    
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Post $post
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {   
 
    }
   
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Post $post
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
 
    }
   
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
 
    }
}

Create the blade files

In this step, create dollowing blade view files:

  • index.blade.php
  • create.blade.php

Now go to resources/views direcotory and create the index.blade.php and create.blade.php file.

resources/views/index.blade.php

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel 9 Generate Unique Slug For Post With Example</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
  </head>
  <body>
    <div class="container">
      <a href="{{ route('posts.create') }}" class="btn btn-success mb-2">Add Post</a> <br>
      <div class="row">
            <div class="col-12">
              
              <table class="table table-bordered" id="laravel_unique_slug_table">
               <thead>
                  <tr>
                     <th>Id</th>
                     <th>Title</th>
                     <th>Slug</th>
                     <th>Description</th>
                  </tr>
               </thead>
               <tbody>
                  @foreach($posts as $post)
                  <tr>
                     <td>{{ $post->id }}</td>
                     <td>{{ $post->title }}</td>
                     <td>{{ $post->slug }}</td>
                     <td>{{ $post->description }}</td>
                  </tr>
                  @endforeach
               </tbody>
              </table>
              {!! $posts->links() !!}
           </div> 
      </div>
    </div>
  </body>
</html>

resources/views/create.blade.php

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel 9 Create Post With Unique Slug</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
  </head>
  <body>
    <div class="container">
 
      <form action="{{ route('posts.store') }}" method="POST" name="add_post">
        {{ csrf_field() }}
 
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <strong>Title</strong>
                    <input type="text" name="title" class="form-control" placeholder="Enter Title">
                    <span class="text-danger">{{ $errors->first('title') }}</span>
                </div>
            </div>
            <div class="col-md-12">
                <div class="form-group">
                    <strong>Description</strong>
                    <textarea class="form-control" col="4" name="description" placeholder="Enter Description"></textarea>
                    <span class="text-danger">{{ $errors->first('description') }}</span>
                </div>
            </div>
            <div class="col-md-12">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>

      </form>

    </div>
  </body>
</html>

Start Your Application

Lastly, start the laravel development server using PHP artisan command:

php artisan serve

If you want to run the project diffrent port so use this below command 

php artisan serve --port=8080  

Test the application using the following url:

http://localhost:8000/posts

Ultimately, the Laravel 9 generates slug tutorial is completed. In this comprehensive post, we figured out how to create a unique slug in laravel 9 using the laravel eloquent sluggable package with example.

Leave a Comment