Share this:

Today, we are going to learn How to create SEO friendly sluggable URL Laravel 9 Example. This tutorial will going to cover how to create SEO friendly slug URL in latest laravel 9 with example.

SEO friendly URLs are URLs that are designed to meet the needs of users and searchers. Specifically, URLs optimized for SEO tend to be short and keyword-rich. URLs are a minor ranking factor search engines use when determining a particular page or resource’s relevance to a search query. While they do give weight to the authority of the overall domain itself, keyword use in a URL can also act as a ranking factor.

Steps on How to create SEO friendly sluggable URL Laravel 9 Example:

  • Step 1: Installing fresh new Laravel 9 Application
  • Step 2: Installing eloquent-sluggable Package
  • Step 3: Creating Database and Migration
  • Step 4: Creating Model
  • Step 5: Creating Route
  • Step 6: Creating Controller
  • Step 7: Creating View Blade File
  • Step 8: Testing
  • Step 9: Conclusion

Also Read: Restrict User Access from IP Address in Laravel 9 Tutorial

Step 1: Installing fresh new Laravel 9 Application

First step, We are going to install a fresh new laravel 9 application. To install a fresh laravel application run the following code in terminal.

composer create-project laravel/laravel seo-slug-app

cd seo-slug-app

Note: seo-slug-app” is a laravel application name.

Installing fresh new Laravel 9 Application
Installing fresh new Laravel 9 Application

Step 2: Installing eloquent-sluggable Package

In next step, we are installing a package called cviebrock/eloquent-sluggable. To install a package run the following command in terminal.

composer require cviebrock/eloquent-sluggable

Now add service provider and alias. Open app/config.php and add the following provider:

'providers' => [
	....
	Cviebrock\EloquentSluggable\ServiceProvider::class,
]
.....

Optionally, publish the configuration file if you want to change any defaults:

php artisan vendor:publish --provider="Cviebrock\EloquentSluggable\ServiceProvider"
Installing eloquent-sluggable Package
Installing eloquent-sluggable Package

Step 3: Creating Database and Migration

Now, Its time to create a database for our application. Open phpmyadmin and create a new database with name “seo-slug-app” (you can name it anything you like!).

Creating Database in phpmyadmin
Creating Database in phpmyadmin

Once you created the database add the database details to .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=seo-slug-app
DB_USERNAME=root
DB_PASSWORD=
Configuration in .env file
Configuration in .env file

Now, We are creating a Items migration file. To create a Items migration run the following command in terminal.

Also Read: Livewire Pagination Laravel 9 Example Tutorial

php artisan make:migration create_items_table

This will create a new items migration which can be found at database/migrations open the file and update with the following code.

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;


class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
           $table->increments('id');
           $table->string('title');
           $table->string('slug');
           $table->timestamps();
       });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop("items");
    }
}
Creating Item Migration file
Creating Item Migration file

Then run the migration with the following code.

php artisan migrate
Migrating file
Migrating file

Step 4: Creating Model

Now we are going to create a Item model. To create a Item model run the following command in terminal.

php artisan make:model Item

You can find the Item model inside app/Models/. Open the file and update with the following code.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;

class Item extends Model
{
    use HasFactory;
    use Sluggable;

    public $fillable = ['title'];

    /**
     * Return the sluggable configuration array for this model.
     *
     * @return array
     */
    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'title'
            ]
        ];
    }
}
Creating Item Model and Updating Item Model - How to create SEO friendly sluggable URL Laravel 9 Example
Creating Item Model and Updating Item Model

Also Read: Enum Model Attribute Casting in Laravel 9 Example

Step 5: Creating Route

Now, Its time to create a route for our application. Open route file from routes/web.php and add the following route into it.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::get('/items', [App\Http\Controllers\ItemController::class, 'index']);
Route::post('/item-create', [App\Http\Controllers\ItemController::class, 'create'])->name('item-create');
Adding Route for our application - How to create SEO friendly sluggable URL Laravel 9 Example
Adding Route for our application

Step 6: Creating Controller

Its time to create a controller. To create a ItemController run the following command in terminal.

php artisan make:controller ItemController

This will create a ItemController file inside app/Http/Controllers. Open the file and update with the following code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Item;

class ItemController extends Controller
{
    /**
     * Get the index name for the model.
     *
     * @return string
    */
    public function index()
    {
    	$items = Item::all();
    	return view('items',compact('items'));
    }

    /**
     * Get the index name for the model.
     *
     * @return string
    */
    public function create(Request $request)
    {
    	$this->validate($request,['title'=>'required']);
    	$items = Item::create($request->all());
    	return back();
    }
}
?>
Creating Item Controller - How to create SEO friendly sluggable URL Laravel 9 Example
Creating Item Controller

Also Read: How to Store JSON in Database Laravel 9

Step 7: Creating View Blade File

At last step, We are creating a view blade file to display our list and creating of item page. Create a items.blade.php inside resources/views and enter the following code.

resources/views/items.blade.php

<!DOCTYPE html>
<html>
<head>
	<title>How to create SEO friendly sluggable URL Laravel 9 Example - LaravelTuts.com</title>
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h2>How to create SEO friendly sluggable URL Laravel 9 Example - LaravelTuts.com</h2><br/>
        <form method="POST" action="{{ route('item-create') }}" autocomplete="off">
            @if(count($errors))
                <div class="alert alert-danger">
                    <strong>Whoops!</strong> There were some problems with your input.
                    <br/>
                    <ul>
                        @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
                        <input type="text" id="title" name="title" class="form-control" placeholder="Enter Title" value="{{ old('title') }}">
                        <span class="text-danger">{{ $errors->first('title') }}</span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <button class="btn btn-success">Create New Item</button>
                    </div>
                </div>
            </div>
        </form>
        <div class="panel panel-primary">
        <div class="panel-heading">Item management</div>
        <div class="panel-body">
            <table class="table table-bordered">
                <thead>
                    <th>Id</th>
                    <th>Title</th>
                    <th>URL</th>
                    <th>Creation Date</th>
                    <th>Updated Date</th>
                </thead>
                <tbody>
                    @if($items->count())
                        @foreach($items as $key => $item)
                            <tr>
                                <td>{{ ++$key }}</td>
                                <td>{{ $item->title }}</td>
                                <td><a href="">{{ URL::to('/') . '/item/' . $item->slug }}</a></td>
                                <td>{{ $item->created_at }}</td>
                                <td>{{ $item->updated_at }}</td>
                            </tr>
                        @endforeach
                    @else
                        <tr>
                            <td colspan="4">There are no data.</td>
                        </tr>
                    @endif
                </tbody>
            </table>
        </div>
        </div>
    </div>
</body>
</html>

Step 8: Testing

That it’s! Now you can test the laravel application. To start the laravel 9 application server run the following command in terminal.

php artisan serve

and open the following URL in any web browser.

http://127.0.0.1:8000/items

Preview:

How to create SEO friendly sluggable URL Laravel 9 Example
How to create SEO friendly sluggable URL Laravel 9 Example

Step 9: Conclusion

Today, We had learn How to create SEO friendly sluggable URL Laravel 9 Example. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Create React JS CRUD using Vite in Laravel 9 Example

Share this:

Categorized in: