Laravel 8 Tutorial - Livewire Route
In this tutorial, we are going to learn about Livewire Route.
So, let's see how we can create a Livewire route.
First of all, let's create a new component. So, switch to the command prompt and just type the command for creating a component:
php artisan make:livewire Home
Now, just open the Home component view. Inside this file, let's add some text here:
<h1>This is Home Component</h1>
Now, go to the web.php file and here, let's create the route for the component:
Route::get('/home',Home::class);
Now, let's check. So, switch to the browser and go to the URL: http://localhost:8000/home. And you can see the component.
Now, let's see how we can pass a parameter to the route. For adding the parameter inside the route, add here {} and inside the curly bracket, add the parameter name. Let's say the parameter name is name.
Route::get('/home{name}',Home::class);
Now, get this parameter to the component class file. Inside the Home component class file, let's create a property here:
public $name;
Now, add here the mount lifecycle hook method. Mount is a hook method that is executed before rendering the view. So, for adding the mount hook, just write here:
public function mount($name)
{
$this->name = $name;
}
Now, let's display the parameter value to the component view. So, just write here:
Hello {{$name}}
Now, save this file and let's check this. So, switch to the browser and in the URL, just add the parameter. So, just type any name here: http://localhost:8000/home/john. And here, you can see the name.
Alright, now let's see how we can pass an optional parameter. For that, just go to web.php. And inside the route, just add here {name?} question mark.
Now, go to the component class file and inside the mount lifecycle hook argument, just add here $name = null as following:
public function mount($name=null)
{
$this->name = $name;
}
Now, the parameter becomes an optional parameter.
Now, let's check. Just remove the name from the URL and you can see the component still showing. And if you add the name here, it's showing the name.
So, in this way, we can create a Livewire Route.