Laravel 8 Tutorial - Livewire With Database

In this tutorial, we are going to learn about Livewire With Database. So, let's see how we can use a database in Livewire.

First of all, let's create a database. Just open phpMyAdmin and create a new database. Let's say the database name is livewiredb.

Now, switch to the project and just open the .env file. Here, just add the database name livewiredb, User root, and Password blank (in my case).

Now, let's create a component. Go to the command prompt and type the following command:


php artisan make:livewire Users

Now, switch to the project and let's create the route for the User component. Just open the web.php file and create the route:


Route::get('/users',Users::class);

Now, go to the database directory, then seeders. Now, open the DatabaseSeeder.php file and write the following codes:


<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
\App\Models\User::factory(10)->create();
}
}

Great, now let's run the migration and then run the database seeder:


php artisan migrate;

Now, run the seeder:


php artisan db:seed

Now, switch to the project, and just go inside the Users.php component class file. Write the following code:


<?php

namespace App\Http\Livewire;

use App\Models\User;
use Livewire\Component;

class Users extends Component
{
public $users;
public function render()
{
$this->users = User::all();
return view('livewire.user-component');
}
}

Now, just open the users.blade.php component view file and add a table to show all the users:


<div>
<section>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
All Users
</div>
<div class="card-body">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>

Now, it's done. So, let's check this. Just switch to the browser and go to the URL /users.

And here, you can see the list of users. So, in this way, you can use a database in Livewire.