DEV Community

Cover image for How to Update Status Data with Toggle Switch in Laravel Livewire
Hilmi Hidayat
Hilmi Hidayat

Posted on • Originally published at codelapan.com

How to Update Status Data with Toggle Switch in Laravel Livewire

Laravel Livewire Toggle Switch - In this post I will share about how to update the data status using toggle switch and without reloading the page in laravel and livewire. With a feature like this, of course it will be very helpful when we want to update data status such as active or inactive user status. So, to change the status of the data, we don't need to open the edit page. On the index page, we can directly change the status of user data by clicking the toggle switch and without reloading the page.

In this post, I will simulate to change the user status to active or inactive. For more details, let's see step by step using the toggle switch in Laravel Livewire below. πŸ‘‡οΈ

Step 1: Install Laravel

//via Laravel Installer
composer global require laravel/installer
laravel new laravel-livewire-toggle-switch

//via Composer
composer create-project laravel/laravel laravel-livewire-toggle-switch
Enter fullscreen mode Exit fullscreen mode

In this first step, we will install laravel (currently version 8) which we will try to implement or use toggle switch in laravel and livewire to change user status. For laravel installation, you can use the laravel installer or use composer like the example above.

Please choose one method you want to use for laravel installation. From the two examples of laravel installation commands above, they will both generate a laravel project with the name laravel-livewire-toggle-switch.

Step 2: Setup Database

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_livewire_toggle_switch
DB_USERNAME=root
DB_PASSWORD=
Enter fullscreen mode Exit fullscreen mode

Next, create a new database to store sample data that we will use in the experiment using the toggle switch in laravel and livewire to change the user status. If you are using xampp as local development, please create a new database at localhost/phpmyadmin. Here I give an example, I created a new database with the name laravel_livewire_toggle_switch. Then don't forget to adjust the DB_DATABASE in the .env file as well as in the example above.

Step 3: Migration & Factory

public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->boolean('isActive');
$table->timestamps();
});
}
Enter fullscreen mode Exit fullscreen mode

Then, open the user migration file and add an isActive column with a boolean data type like the code above.

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

If you have added the isActive column, then run the php artisan migrate command to migrate the migration files to the database.

public function definition()
{
return [
'name' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
'isActive' => false
];
}
Enter fullscreen mode Exit fullscreen mode

Okay. Now let's generate dummy data for the users table. Open the UserFactory.php file, add isActive and its value is false.

php artisan tinker
User::factory()->count(10)->create()
Enter fullscreen mode Exit fullscreen mode

After adding isActive in UserFactory.php, we can now execute it using tinker. Open a terminal, then run the commands as above sequentially. With the command User::factory()->count(10)->create(), we will generate 10 dummy user data.

Step 4: Setup Route

Route::get('/', function () {
return view('welcome',[
'users' => App\Models\User::all()
]);
});
Enter fullscreen mode Exit fullscreen mode

In this fourth step, we only need to update the existing route, i.e. add data from the User model.

Step 5: Setup View

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
        <title>Laravel Livewire Toggle Switch</title>
    </head>
    <body>
        <div class="container my-5">
            <h2 class="fs-4 fw-bold text-center">Laravel Livewire Toggle Switch</h2>
            <div class="row">
                <div class="col-md-8 offset-md-2">
                    <table class="table text-center">
                        <thead>
                            <tr>
                                <th scope="col">#</th>
                                <th scope="col">Name</th>
                                <th scope="col">Email</th>
                                <th scope="col">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse ($users as $key => $user)
                            <tr>
                                <th scope="row">{{ ++$key }}</th>
                                <td>{{ $user->name }}</td>
                                <td>{{ $user->email }}</td>
                                <td>TBA</td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="4">Data not Found</td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Then, open the welcome.blade.php file. Change the existing code with the code as above. With the code above, we will only display a table that contains data from the users table.

Step 6: Generate Livewire Component

composer require livewire/livewire
Enter fullscreen mode Exit fullscreen mode

In this sixth step, we need to install livewire. To install livewire, we can run the command as above.

...
    @livewireStyles
</head>
<body>
    ...

    @livewireScripts
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

After installing livewire, add @livewireStyles in the head tag and @livewireScripts before the end of the body tag.

php artisan make:livewire UserStatus
Enter fullscreen mode Exit fullscreen mode

Next, we can generate livewire components with the command as above.

The livewire component that has been generated with the above command will be located in the directory;
CLASS: app/Http/Livewire/UserStatus.php
VIEW: resources/views/livewire/user-status.blade.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Illuminate\Database\Eloquent\Model;

class UserStatus extends Component
{
    public Model $model;

    public $field;

    public $isActive;

    public function mount()
    {
        $this->isActive = (bool) $this->model->getAttribute($this->field);
    }

    public function updating($field, $value)
    {
        $this->model->setAttribute($this->field, $value)->save();

    }

    public function render()
    {
        return view('livewire.user-status');
    }
}
Enter fullscreen mode Exit fullscreen mode

Then, open the UserStatus.php file and change the code to be like the code above.

<div class="form-check form-switch">
  <input class="form-check-input"  wire:model.lazy="isActive" type="checkbox" role="switch" @if($isActive) checked @endif>
</div>
Enter fullscreen mode Exit fullscreen mode

Next, in the user-status.blade.php file, enter the code as above. The code above is a toggle switch component from bootstrap which we add dirty state wire:model.lazy and we give the condition if $isActive is 1 or true then it will add the checked attribute.

<td>TBA<td>
Enter fullscreen mode Exit fullscreen mode

Now, open the welcome.blade.php file and look for the code as above, then replace it with the code as below.

<td>
    @livewire('user-status', ['model' => $user, 'field' => 'isActive'], key($user->id))
</td>
Enter fullscreen mode Exit fullscreen mode

With the code above, we'll call the livewire user-status.blade.php component that was generated earlier, and pass the $user model and the isActive field and with the id parameter from that user's data.

Step 7: Testing

Toggle Switch Laravel Livewire
Alright, after going through the step by step to create or use the toggle switch to change the data status in laravel livewire, now is the time to test. Please run the laravel project, then open the project in the browser. Try clicking the toggle switch and looking at the user's status in the users table, then the result is that we have succeeded in updating the user's status with the toggle switch without reloading the page.

Happy coding. πŸ₯‚

Top comments (1)

Collapse
 
vhomevungtau profile image
vhomevungtau

How to update toogle when update data by form?