This episode is for members only

Sign up to access "Build a File Marketplace with Laravel" right now.

Get started
Already a member? Sign in to continue
Playing
11. Automatically generating the slug from the product title

Episodes

0%
Your progress
  • Total: 3h 32m
  • Played: 0m
  • Remaining: 3h 32m
Join or sign in to track your progress

Transcript

00:00
So this is where Livewire really shines, and the reason that we've used it for these forms. When we enter a title inside of here, when we click away from this, we want the slug to be automatically generated. Now we can do this with a hook over on the create product Livewire component.
00:15
So just down here, the way the hook works within Livewire is we prefix this with the action that's happened. So for example, updated. Then we give the name of either the property, or in this case, our state array, and the name of the field. When that gets updated, we want to perform an action on it. So in our case, if we just had a property called title, it would be updated title. But for
00:39
us, we've got state title. So when the title within this state is updated, then we want to do something in here. What do we want to do? Well, we want to update the slug within the state to slugified version of the title. So we're going to go ahead and access the state array. We're going to go ahead and set the slug. Laravel already has a slug string helper, so we can bring in illuminate
01:04
support string and just say slug. And then we actually get the title property passed into this method. So then we can just go ahead and slug the title. And that's pretty much all we need to do. Very, very short. So let's go ahead and check it out. So I'm going to say a product name here. When I click down, you can see sure enough that has been placed into the slug field.

Episode summary

In this episode, we take a closer look at how to automatically generate a product slug from the product title using Livewire. This is one of those nice user experience touches that saves time and prevents mistakes.

We start by explaining how Livewire makes it easy to listen for changes to form fields. When the user enters a title for the product and then clicks away (or otherwise leaves the input field), we want the slug to update automatically to a URL-friendly version. To do this, we set up a specific Livewire hook: updatedStateTitle. This method fires whenever the title field within our state array changes.

Inside the hook, we use Laravel's handy string helper to convert the title into a slug format and update our state accordingly. It's just a few lines of code, but it works like magic—type in your product name, tab out, and poof, the slug appears ready to go!

So by the end of the episode, you'll see how quick this is to set up, and you'll have a smoother, smarter form on your hands.

Episode discussion

No comments, yet. Be the first!