Laravel 9 Livewire Generate New Slug Tutorial Example

The Livewire Generate New Slug Tutorial will teach you a simple and best way for generating a slug in a Laravel application while using the livewire package.

In this article will give you the complete information on how to create a unique slug in the Laravel web application using the Livewire library. Let us first summarize the main steps we are going to discuss here.

To make the Laravel livewire create slug example work, we need to first create a new Laravel app, install the livewire plugin, then create the required model, view and controller. Finally, we will create routes and connect those routes to the controller to invoke the controller and model’s business logic.

The Laravel Livewire library allows build up of reactive, functional, and dynamic interfaces using the Laravel Blade, a language that your Laravel templates rely on.

Generate Slug with Livewire Package

Step 1: Create Laravel Project

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

Use the composer package as shown below to create a new Laravel app.

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

Navigate to the projects root directory.

cd livewire_slug

Step 2: Add Database Details

Populate the .env file with database credentials as shown below.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=db_user_name
DB_PASSWORD=db_password

In case you are using macOS, for the MAMP local server in it, you should add UNIX_SOCKET and DB_SOCKET credentials, as below.

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

Step 3: Install Livewire Package

Since you are in the project’s root directory, install the livewire package for your Laravel project.

composer require livewire/livewire

Step 4: Add Eloquent Sluggable Package

To make the new slug functionality work properly, add the Eloquent Sluggable Package. The library will help you generate a slug in Laravel.

You may run the following command to install this package.

composer require cviebrock/eloquent-sluggable

Step 5: Publish Sluggable Config File

Since all the required packages are installed now, you should now register the Sluggable package to start creating slugs according to the Laravel Eloquent Models.

The command below will publish a configuration file in Laravel.

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

Step 6: Create Model and Migrations

We will now create models and relevant database migrations. The migration files will help to create database tables.

Execute the command below to create a new model and relevant migration simultaneously.

php artisan make:model Livewire_Slug -m

Open app/Models/Livewire_Slug.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 Livewire_Slug extends Model
{
    use HasFactory,Sluggable;
    protected $fillable = [
        'post_title',
        'slug',
    ];
    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'post_title'
            ]
        ];
    }
}

Open database/migrations/create_livewire_slug_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 CreateLivewire_SlugTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('posts_title');
            $table->string('slug');            
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

You may now go to console, and type the recommended command to execute this migration.

php artisan migrate

This creates a new table in the database with the specification as in your migration file.

Step 7: Create Route in Laravel

Go to the routes/web.php file and define a new route as below.

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

Step 8: Set Up Livewire Component

Now, you will have to execute the command below to generate the livewire posts components.

php artisan make:livewire post-component

Eventually, the command above creates two files at the given paths:

app/Http/Livewire/Livewire_SlugComponent.php
resources/views/livewire/livewire_slug-component.blade.php

You may now open and edit the code below in app/Http/Livewire/Livewire_SlugComponent.php file:

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

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

Then open and edit the resources/views/livewire/blog-component.php file with the code below:

<div>
    <form wire:submit.prevent="store">
        <div class="form-group">
            <label for="post_title" class="mb-2"><strong>Post Title</strong></label>
            <div class="col-md-12 mb-3">
                <input wire:model="post_title" type="text"
                    class="form-control @error('post_title') is-invalid @enderror" autofocus>
                @error('post_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 Post
                </button>
            </div>
        </div>
    </form>
    <table class="table mt-5">
        <thead>
            <tr>
                <th>Post Title</th>
                <th>Slug</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($posts as $post)
            <tr>
                <td>{{ $post->post_title }}</td>
                <td>{{ $post->slug }}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>

Step 9: Set Up Blade View

Finally, make sure to head over to resources/views/livewire/ folder, you may now create the welcome.blade.php file in this directory and insert all the code given below in this file.

Edit resources/views/livewire/welcome.blade.php file as follows.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <title>Implement Slug in Laravel Livewire Example - scratchcoding.dev</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('post-component')
    </div>
    @livewireScripts
</body>
</html>

Step 10: Start Laravel App

You can now start the Laravel development server, by going to the terminal and executing the command below to run the app.

php artisan serve

Go to your browser and type in the URL below to view the app.

http://127.0.0.1:8000/generate-slug

You may see the Blog Title along with the slug in the following format.

Blog TitleSlug
Laravel Create New Slug Examplelaravel-create-new-slug-example
Laravel Create New Projectslaravel-create-new-projects

Conclusion

To sum up, Livewire works on AJAX calls to interact with the servers. This guide was to make you learn how to generate slug in the Laravel app and store that slug in the database using the livewire package.

Hope this guide will help you generate new slugs easily in Laravel.