How to Fetch records using Livewire from MySQL in Laravel

Livewire provides a simple abstraction over AJAX that allows us to easily fetch records from the database and update the UI without having to write any JavaScript.

In this tutorial, I show how you can fetch records using Livewire from the MySQL database in Laravel 9.

How to fetch records using Livewire from MySQL in Laravel


Contents

  1. Install Livewire
  2. Add Database configuration
  3. Create a Table
  4. Create Model
  5. Create Controller
  6. Create Route
  7. Create Livewire Component
  8. Create View
  9. Output
  10. Conclusion

1. Install Livewire

You can skip this step if Livewire is already installed in your project.

Run following command to install Livewire –

composer require livewire/livewire

2. Add Database configuration

Open .env file to update the database connection.

Specify the host, database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

3. Create a Table

  • Create a new table employees using migration.
php artisan make:migration create_employees_table
  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_employees_table and open it.
  • Define the table structure in the up() method.
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
       $table->id();
       $table->string('emp_name',60);
       $table->string('email',80);
       $table->string('city',100);
       $table->timestamps();
    });
}
  • Run the migration –
php artisan migrate
  • The table is been created and I added some records to it.

4. Create Model

  • Create Employees Model –
php artisan make:model Employees
  • Open app/Models/Employees.php file.
  • Specify mass assignable Model attributes – emp_name, email, and city using the $fillable property.

Completed Code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{
    use HasFactory;
    protected $fillable = [ 
        'emp_name','email','city'
    ];
}

5. Create Controller

Create EmployeesController controller.

php artisan make:controller EmployeesController

Create 1 method –

  • index() – Load index view.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class EmployeesController extends Controller
{
    public function index(){
        return view('index');
    }
}

6. Create Route

  • Open routes/web.php file.
  • Define 1 route –
    • / – Load index view.
<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\EmployeesController;

Route::get('/', [EmployeesController::class, 'index']);

7. Create Livewire Component

Create fetchemployees component –

php artisan make:livewire fetchemployees

This will create 2 files –

  • app/Http/Livewire/Fetchemployees.php
  • resources/views/livewire/fetchemployees.blade.php

Fetchemployees.php

  • Open app/Http/Livewire/Fetchemployees.php file.
  • Create 2 properties –
    • $records – Store fetch data.
    • $employeeid – Use for data binding. Read entered value in the textbox.
  • Create 2 methods –
    • fetchbyid() – Fetch a record from employees table where $this->employeeid in id field. Assign fetched record to $this->records.
    • fetchall() – Fetch all records from the employees table and assign to $this->records.

Completed Code

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Employees;

class Fetchemployees extends Component
{
     public $records;
     public $employeeid = 0;

     // Fetch record by ID
     public function fetchbyid(){
          $this->records = Employees::orderby('id','asc')
                           ->select('*')
                           ->where('id',$this->employeeid)
                           ->get(); 
     }

     // Fetch all records
     public function fetchall(){
          $this->records = Employees::orderby('id','asc')->select('*')->get(); 
     }

     public function render(){
          return view('livewire.fetchemployees');
     }
}

fetchemployees.blade.php

  • Open resources/views/livewire/fetchemployees.blade.php file.
  • Create a textbox to enter employee id. Add wire:model="employeeid", Here, employeeid is a public property of the Fetchemployees component class.
  • Create 2 buttons –
    • 1st button is used to fetch a record by entered employee id in the textbox on click – wire:click="fetchbyid". Here fetchbyid is method name in the component class.
    • 2nd button is used to fetch all records on click – wire:click="fetchall". Here, fetchall is method name in the component class.
  • To display fetched records create a <table >. Loop on $records to create new <tr > if it is not empty.

Completed Code

<div>

    <!-- Fetch record by ID -->
    <input type='number' wire:model="employeeid" >
    <input type='button' value='Fetch record by ID' wire:click="fetchbyid" >
    <br/><br>

    <!-- Fetch all records -->
    <input type='button' value='Fetch all records' wire:click="fetchall">
    <br><br>

    <!-- List records -->
    <table border='1' style='border-collapse: collapse;'>
        <thead>
            <tr>
               <th>Name</th>
               <th>Email</th>
               <th>City</th>
            </tr>
        </thead>
        <tbody>
            @if(!empty($records))
                 @foreach($records as $record)
                     <tr>
                         <td>{{ $record->emp_name}}</td>
                         <td>{{ $record->email}}</td>
                         <td>{{ $record->city}}</td>
                     </tr>
                 @endforeach
            @endif
        </tbody>
    </table>

</div>

8. Create View

Create index.blade.php file in resources/views/ folder.

Include fetchemployees component – <livewire:fetchemployees />  and script.

Completed Code

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>How to fetch records using Livewire from MySQL in Laravel</title>
   <style type="text/css">
   table td{
       padding: 5px;
   }
   </style>
</head>
<body>

   <livewire:fetchemployees /> 

   @livewireScripts
</body>
</html>

9. Output

View Output


10. Conclusion

In the example, I show you how you use livewire to fetch all records and fetch record by id. Make sure to include @livewireScripts in the view otherwise, events do not work and data will not fetch.

If you found this tutorial helpful then don't forget to share.

2 thoughts on “How to Fetch records using Livewire from MySQL in Laravel”

Leave a Comment