• Hello, Visitor
  • Monday, June 24, 2024
Search Result
Home » Laravel » Livewire » Auto Generate Slug with Laravel Livewire

Auto Generate Slug with Laravel Livewire

Hello friends, today in this blog you’ll learn how to generate slugs automatically with the title you entered by using Laravel Livewire.

Basically, Slug is a hyphen (-) based string, which is used as a URL of a post or a product. Suppose you have a blog website and you uploaded a blog post. Now to read the blog post you need a unique URL for your post. Yes, you can also use post id, but the slug is more SEO-friendly than ids. You can also check the video tutorial.

Video Tutorial:



Step 01: Add Function & Variabled in Class File

Open your component class file and add the variables given bellow

public $title, $slug;

Now, create a function to generate a slug automatically

public function generateSlug()
{
    $this->slug = Str::slug($this->title);
}

Also, don't forget to import the Str class

use Illuminate\Support\Str;


Step 02: Add Livewire Model & Event in Blade File

Open your component blade PHP file and use the variables as wire:model in input fields for title & slug

<input type="text" name="" id="" wire:model='title' class="form-control" placeholder="Enter title" />
<input type="text" name="" id="" wire:model='slug' class="form-control" placeholder="Enter slug" />



After that in title input field, add the generateSlug() function as a livewire click event

<input type="text" name="" id="" wire:model='title' wire:keyup='generateSlug' class="form-control" placeholder="Enter title" />



Now, when you write your title in the title input field, it will generate a slug automatically according to your title.


Output:



Thanks for reading. Hope it will help you.



Leave a Reply

You must Login to add a comment