LARAVEL Tutorial


Laravel 7 Generate And Create Slug URL Example


In this laravel tutorial, you will learn how to create unique slug from title in laravel web applications using the laravel sluggable package

Laravel Create Unique Slug From Title Example

  • Install Laravel Application
  • Configure Database Detail
  • Install Eloquent Sluggable Package 
  • Run Migration
  • Create Routes
  • Generate Controller By Artisan
  • Create Blade View
  • Start Development Server

Install Laravel Application

First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:

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

If you want to install a specific version of laravel, you can follow the following tutorial

https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer

Configure Database Detail

After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=root

Install Eloquent Sluggable Package

Next, open command prompt and run the following command to 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 By Artisan

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'); 
    } 
} 

Run Migration

Before you will run php artisan migrate command. Go to app/providers/AppServiceProvider.php and update the below code :

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

Next, go to command prompt and run the following command:

php artisan migrate

OR

php artisan migrate:fresh

This php artisan migrate command creates a table in your database.

 Next, 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'
            ]
        ];
    }
 }

Create Routes

Next step, go to routes/web.php file and update the following routes into your file:

//display users list
Route::resource('posts', 'PostController'); 

Generate Controller By Artisan

Now, you need to generate or create a controller file using php artisan command, so use the php artisan make:controller command and generate/create a new controller file:

php artisan make:controller PostController  --resource

After that, go to App/Http/Controllers/ directory and find the created AutoCompleteSearchController file and update the following code into your file:

<?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('list',$data);
    }
   
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('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 Blade Views

Next, you need to create a blade views file, so go resource/views directory and create the following blade views file.

Go to resource/views/ then create some new blade view files name list.blade.php  and create.blade.php and update the following code:

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 - w3alert.com</title>

    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

  </head>
  <body>
    <div class="container mt-5">
      <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">
               <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- w3alert.com</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

  </head>
  <body>

    <div class="container mt-5">

      <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 development server

You can use the following command artisan command to start the development server:

php artisan serve

The final step, go to your browser and type the below-given URL into your browser:

http://localhost:8000/posts

OR

http://localhost/laravel-unique-slug-app/public/posts