Laravel 10 Livewire Generate New Slug Tutorial Example

Last Updated on by in Laravel

In this comprehensive guide, you will learn how to generate a new slug in Laravel using Livewire, a powerful framework for building modern web applications.

Slugs are user-friendly, SEO-optimized strings that represent the title of an item in a URL. Generating a unique slug for your blog titles enhances readability and search engine ranking.

We cover the key steps:

  • Creating the BlogComponent: Define a Livewire component with necessary properties and methods.
  • Rendering Blogs: Fetch and display the latest blogs using the render() method.
  • Generating Slugs: Use SlugService from the EloquentSluggable package to generate slugs based on the blog title.
  • Storing Blog: Create a new blog entry with the generated slug using the store() method.

This tutorial will guide you through setting up the Livewire component and working with slugs, providing step-by-step instructions to create a smooth user experience for managing blogs.

How to Generate Slug in Laravel 10 with Livewire Package

  • Step 1: Create New Laravel Project
  • Step 2: Insert Database Details in ENV
  • Step 3: Add Livewire Library in Laravel
  • Step 4: Add Eloquent Sluggable Package
  • Step 5: Publish Sluggable Config File
  • Step 6: Create Model and Migrations
  • Step 7: Create Route in Laravel
  • Step 8: Set Up Livewire Component
  • Step 9: Set Up Blade View
  • Step 10: Start Laravel App

Create New Laravel Project

The first section of this guide advice you to run the suggested command for installing a brand new laravel app.

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

Don’t forget to get inside the app’s root:

cd Blog

Insert Database Details in ENV

This step shows how to connect database to laravel app by adding the database credentials inside the .env configuration file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Add Livewire Library in Laravel

Its easy to install the livewire package into the laravel; you have to open the terminal, type command, and execute to begin the installation process.

composer require livewire/livewire

Add Eloquent Sluggable Package in Laravel

In the further step, you have to install the eloquent sluggable package, and this library will help you generate slug in laravel.

Make sure to run the following command to install the plugin.

composer require cviebrock/eloquent-sluggable

Publish Sluggable Config File

Now laravel slug package has been installed; now, you have to register this package for starting the creation of slugs as per the laravel eloquent models.

Let us execute the command to publish the configuration file in laravel.

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

Create Model and Migrations

Let us create a migration and model files; theoretically, these files help in creating the table into the database.

Run the below command to generate a migration and model simultaneously.

php artisan make:model Blog -m

Open app/Models/Blog.php and add the values in the newly generated models file.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;

class Blog extends Model
{
    use HasFactory,Sluggable;
    protected $fillable = [
        'blog_title',
        'slug',
    ];
    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'blog_title'
            ]
        ];
    }
}

Open database/migrations/create_blogs_table.php and insert the table properties within the migration file.

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

Now, go to console, type the recommended command to run the migration.

php artisan migrate

Create Route in Laravel

Open the routes/web.php in this file you need to define the route.

<?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::view('/generate-slug', 'livewire.welcome');

Set Up Livewire Component

Next, you have to execute the following command to generate the livewire blog components.

php artisan make:livewire blog-component

Eventually, the suggested command created two files on the following path:

app/Http/Livewire/BlogComponent.php
resources/views/livewire/blog-component.blade.php

Open and update the below code in app/Http/Livewire/BlogComponent.php file:

<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Blog;
use \Cviebrock\EloquentSluggable\Services\SlugService;

class BlogComponent extends Component
{
    public $blog_title;
    public $slug;
    public function render()
    {
        $blogs = Blog::latest()->take(7)->get();
        return view('livewire.blog-component', compact('blogs'));
    }
    public function generateSlug()
    {
        $this->slug = SlugService::createSlug(Blog::class, 'slug', $this->blog_title);
    }
    public function store()
    {
        Blog::create([
            'blog_title' => $this->blog_title,
            'slug'  => $this->slug
        ]);
    }
}

Open and update the below code in resources/views/livewire/blog-component.php file:

<div>
    <form wire:submit.prevent="store">
        <div class="form-group">
            <label for="blog_title" class="mb-2"><strong>Blog Title</strong></label>
            <div class="col-md-12 mb-3">
                <input wire:model="blog_title" type="text"
                    class="form-control @error('blog_title') is-invalid @enderror" autofocus>
                @error('blog_title')
                <span class="invalid-feedback">
                    <strong>{{ $message }}</strong>
                </span>
                @enderror
            </div>
        </div>
        <div class="col-md-12">
            <div class="d-grid">
                <button type="submit" class="btn btn-dark">
                    Create Blog
                </button>
            </div>
        </div>
    </form>
    <table class="table mt-5">
        <thead>
            <tr>
                <th>Blog Title</th>
                <th>Slug</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($blogs as $blog)
            <tr>
                <td>{{ $blog->blog_title }}</td>
                <td>{{ $blog->slug }}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>

Set Up Blade View

In the last step, make sure to head over to resources/views/livewire/ folder, you have to create the welcome.blade.php file in this directory and after that insert all the given below code in the suggested file:

Update resources/views/livewire/welcome.blade.php file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <title>Implement Slug in Laravel Livewire Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
    @livewireStyles
</head>
<body>
    <div class="container mt-3">
        @if (session()->has('message'))
        <div class="alert alert-primay">
            {{ session('message') }}
        </div>
        @endif
          @livewire('blog-component')
    </div>
    @livewireScripts
</body>
</html>

Start Laravel App

The last task is to start the laravel development server, go to terminal and run the given below command to run the app.

php artisan serve

Hit the below url on the browser to view the app.

http://127.0.0.1:8000/generate-slug

Laravel Livewire Generate New Slug Tutorial Example

Conclusion

In this tutorial, you’ve learned how to generate and store unique slugs for your blog titles using Livewire in Laravel. This feature helps you create SEO-friendly URLs and streamline your web application’s URL structure management.

You’re now ready to integrate this knowledge to your projects. Happy coding!

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.