Laravel 7/6 Create/Generate Unique Slug Example

Laravel 7/6 Create/Generate Unique Slug Example

Laravel create or generate unique slug for the blog post. In This tutorial, we will demonstrate to you how to make unique slug or seo friendly slug url for each post in laravel using the cviebrock eloquent sluggable laravel package.

When we create a blog post project in laravel, we need to create or generate unique slug for each blog post. This tutorial will help you in generating or creating a unique slug for each post in your laravel blog post project.

Laravel Generating Unique Slug

Just follow the below steps and create unique slug for a blog post or any slug seo friendly slug url in laravel:

  • Install Laravel Fresh New Setup
  • Setup Database Credentials
  • Install Eloquent Sluggable Package
  • Generate Model and Migration
  • Create Resource Route & Controller
  • Create the blade view
  • Start Development Server
  • Conclusion

1). Install Laravel Fresh New Setup

We need to install laravel 6 fresh application using below command, Open your command prompt and run the below command :

composer create-project --prefer-dist laravel/laravel Blog

After successfully install laravel 6 Application, Go to your project .env file and set up database credential and move next step.

2. Setup Database Credentials

In this step, we will set database credentials in the .env file. Let’s open .env file.

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

3. Install Eloquent Sluggable Package

Next, open command prompt and go to your project root directry like cd/project name. And type the below command to install the eloquent sluggable package for generating unique slug of posts:

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"

4. Generate Model and Migration

Now we will create a table name posts and it’s migration file. use the below command :

php artisan make:model Post -m

It command will create one model name Post and also create one migration file for the post table. After successfully run the command go to database/migrations file and put the below here :

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

If you found any query builder error in command prompt go to  => app\Providers\AppServiceProvider.php and put the below code here :

 use Illuminate\Support\Facades\Schema;
  
 public function boot()
 {
     Schema::defaultStringLength(191);
 } 

And then run this below command :

 php artisan migrate:fresh

Now, add the fillable property inside Post.php file.

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

5. Create Resource Route & Controller

Create the PostController using the below command:

php artisan make:controller PostController  --resource

This command will create a controller name PostController and also inside by default seven methods like index, store, create, update, destroy, show, edit.

Next, We need to add the resource route. Go to routes/web.php put the below routes here :

<?php 

 Route::get('/', function () {
     return view('welcome');
 });
 
Route::resource('posts', 'PostController'); 

Next open controller, Go to app/HTTP/Controller/PostController and put the below code here :

<?php
  
namespace App\Http\Controllers;
  
use App\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)
    {

    }
    
}

6. Create the blade view

In this step, we need to create blade view files, Go to app/resources/views/ and create one folder name post. Inside the post, folder creates the following blade files.

After successfully create the post folder than create 2 following blade files.

  • List.blade.php
  • Create.blade.php

List.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 Generate Unique Slug For Post With Example - Tutsmake.com</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <style>
    body{
    background-color: #25274d;
    }
    .container{
    background: #ff9b00;
    padding: 4%;
    border-top-left-radius: 0.5rem;
    border-bottom-left-radius: 0.5rem;
    }
    </style>
  </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>

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 Create Post With Unique Slug- Tutsmake.com</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <style>
    body{
    background-color: #25274d;
    }
    .container{
    background: #ff9b00;
    padding: 4%;
    border-top-left-radius: 0.5rem;
    border-bottom-left-radius: 0.5rem;
    }
    </style>
  </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>

7. Run Development Server

In this step, we will use the PHP artisan serve command. It will start your server locally

php artisan serve

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

php artisan serve --port=8080

Now we are ready to run our example so run bellow command to quick run.

http://localhost:8000/posts

8. Conclusion

In this article, We have learned how to create a unique slug for posts in laravel 6 using the laravel eloquent sluggable package with example. Our examples run quickly.

You may like

  1. Laravel Tutorial From Scratch | Step By Step
  2. Laravel 7 Ajax CRUD(DataTables Js) Tutorial Example
  3. Laravel – Ajax CRUD (Operation) Application Example
  4. Laravel 6 Angular JS CRUD Example Tutorial
  5. Upload Files/Images to Amazon s3 Cloud Using Laravel 6 Filesystem
  6. Laravel 7 CKEditor with Image Upload
  7. Ajax Image Upload In Laravel Tutorial Example From Scratch
  8. Laravel 7 Intervention Upload Image Using Ajax – Example
  9. Laravel Upload Image to Database with Validation
  10. Send Email Example Laravel
  11. Generate OR Create PDF In Laravel 6 Example
  12. Simple Generator or Create Qr Code Example Laravel
  13. Laravel Custom Cron Schedule Example Tutorial
  14. Laravel 6 Github Login Example

AuthorTuts Make

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Codeigniter, Vue JS, Angular JS, React Js, WordPress and Bootstrap from a starting stage.

One reply to Laravel 7/6 Create/Generate Unique Slug Example

  1. Thanks for the article. I have one question though. How do you provide uniqueness of the generated slug in the database? If I have two posts with the same title, like ‘My New Cool Post’, there should be a mechanism to generate two unique slugs, such as ‘my-new-cool-post’ and ‘my-new-cool-post-1’.

Leave a Reply

Your email address will not be published. Required fields are marked *