Thursday, December 26, 2024
Google search engine
HomeLanguagesLaravel 8 Create Unique Slug Tutorial Example

Laravel 8 Create Unique Slug Tutorial Example

Laravel 8 create or generate unique slug. In this tutorial, you will learn how to create unique slug or seo friendly slug URL before save to database in laravel 8 app using cviebrock/eloquent-sluggable laravel 8.

Sometimes, you create a blog post project in laravel 8 app. At that time, need to create or generate unique slug for each blog post in laravel 8 app. So, this tutorial will guide you step by step on generating or creating a unique slug for each post in your laravel 8 blog post project.

Create Unique Slug in Laravel 8 using cviebrock/eloquent-sluggable

  • Step 1 – Install Laravel 8 App
  • Step 2 – Connecting App to Database
  • Step 3 – Install Eloquent Sluggable Package
  • Step 4 – Build Model and Migration
  • Step 5 – Add Routes
  • Step 6 – Create Controller using Artisan Command
  • Step 7 – Create the blade view
  • Step 8 – Start Development Server

Step 1 – Install Laravel 8 App

First of all, Execute the following command on terminal to install laravel 8 app. So, open your command prompt and execute the following command:

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

Step 2 – Connecting App to Database

In this step, Visit laravel 8 app project root directory and open .env file. Then add database credentials in the .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

Step 3 – Install Eloquent Sluggable Package

In this step, 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"

Step 4 – Build Model and Migration

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

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

Now, add the fillable property in Post.php file, which is placed inside app/models directory:

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

Step 5 – Add Routes

In this step, visit the routes directory and open web.php. Then add the following routes to web.php file:

<?php 

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

Step 6 – Create Controller using Artisan Command

In this step, execute the following command on terminal to create the PostController.php file:

php artisan make:controller PostController

Now, visit app/HTTP/Controller directory and open PostController.php file. And add the following code into it:

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

    }
    
}

Step 7 – Create the blade view

In this step, create dollowing blade view files:

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

Visit /resources/views/ and create the list.blade.php and create.blade.php file.

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

Step 8 – Run Development Server

In this step, Execute the PHP artisan serve command on terminal to start development server:

php artisan serve

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

php artisan serve --port=8080

Now, open the browser and hit the following URL on it:

http://localhost:8000/posts

Conclusion

Laravel 8 generate slug before save tutorial, You have learned how to create a unique slug in laravel 8 using the laravel eloquent sluggable package with example.

Recommended Laravel Posts

RELATED ARTICLES

Most Popular

Recent Comments