Making your first component with Laravel Livewire
Today, I will show you how to make your first component with Laravel Livewire. To do so, you have to make sure that, you have installed livewire on your laravel project. If you don’t know how to do that, check this
Let’s get started…
Once you installed livewire, you should able to see livewire commands on php artisan
.
Now, run php artisan make:livewire PostList
to your terminal that will show a screen like that-
COMPONENT CREATED 🤙
CLASS: app/Http/Livewire/PostList.php
VIEW: resources/views/livewire/post-list.blade.php
_._
/ /o\ \ || () () __
|_\ /_| || || \\// /_\ \\ // || |~~ /_\
|`|`| || || \/ \\_ \^/ || || \\_
Congratulations, you've created your first Livewire component! 🎉🎉🎉
Would you like to show some love by starring the repo? (yes/no) [no]:
>
Now, hit enter
to say no
by default.
By doing so, it just created a class on app/Http/Livewire/PostList.php
and a view file resources/views/livewire/post-list.blade.php
.
Now run php artisan make:model Post -mc
to create Post
model, migration and controller.
I just added a column on post
migration like so-
$table->text('body');
Define a Route
Imagine, I want to access all of my posts from the database. So, I will access http://127.0.0.1:8000/posts
all posts.
web.php
Route::get('/posts', 'PostController@index');
Update PostController
In the PostController
, I just add the index()
method like so-
class PostController extends Controller
{
public function index()
{
return view('posts');
}
}
Go to views/posts.blade.php
file and add which livewire view you want to show in @livewire()
. For our case, it should be post-list
that we have created via livewire command.
So, it would be-
@livewire('post-list')
Let’s go to resources/views/livewire/post-list.blade.php
and define how you show your data.
<div>
@foreach($posts as $post)
<p>{{ $post->body }}</p>
@endforeach
</div>
Update PostList class.
Finally, need to update the render()
method inside the app/Http/Livewire/PostList.php
class. Here, I want to fetch all the data from posts
table.
use App\Post;
use Livewire\Component;
class PostList extends Component
{
public function render()
{
$posts = Post::latest()->get();
return view('livewire.post-list', [
'posts' => $posts
]);
}
}
Done, now if you go to http://127.0.0.1:8000/posts, you will get the list of the posts.
Notes: Inside the components of the post, you can write your code with Laravel expression. It supports most of the laravel style.
Get the full code on Github
Than you.