Laravel 8 Tutorial - Livewire Components
In this tutorial, we are going to learn about Livewire Components.
Components are the building blocks of any Livewire application, and a typical Livewire application will have many of these.
Alright, now let's see how we can create a component in Livewire.
For that, switch to the command prompt and just type the command:
php artisan make:livewire Post
This command will create two files: a class file and a view file. The class file is created inside the app\Http\Livewire
directory, and here you can see the Post.php
class file.
Inside this class file, there is a render
function that returns a view, which is created inside the Resources\views\livewire\post.blade.php
file.
Inside this view file, add the text:
<h1>Post Component</h1>
Now, let's add the route for this component. So, go to the web.php
file and just type:
Route::get('/post',Post::class);
Make sure you have imported the Post
Component on top as follows:
use App\Http\Livewire\Post;
Now, save the file and let's check this. First, run the application:
Php artisan serve
Now, switch to the browser and go to the URL http://localhost:8000/post
. And here, you can see the component.
Now, let's see how we can create inline components. Components without a view (.blade.php
) file are called inline components.
So, for creating inline components, just type the command:
php artisan make:livewire User --inline
Alright, inline component created. Now, switch to the project and inside the app\Http\Livewire
directory, you can see the User
component.
Just open this. Inside this render
function, you can see the template code written inside this blade.
Now, let's add some text here:
<h1>User Inline Component</h1>
Now, let's create the route for this. So, go to the web.php
file and just write:
Route::get('/user',User::class);
Now, let's check it. So, switch to the browser and just go to the URL http://localhost:8000/user
. And you can see the component.
Alright, now let's see how we can render a component inside a Laravel blade file. So, just go to any blade file, let's open the welcome.blade.php
file, and add @livewireStyles
in the head tag and @livewireScripts
just before the closing body tag.
Now, for rendering the component inside the body, just write:
@livewire('post')
@livewire('user')
Now, let's check, and you can see the component.
So, in this way, we can create and render Components in Livewire.