How to Update Status Data with Toggle Switch in Laravel Livewire
Tags: webdev, laravel, programming
Published: 2021-11-01 04:30:31

**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
```
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=
```
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
```php
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();
});
}
```
Then, open the user migration file and add an isActive column with a boolean data type like the code above.
```
php artisan migrate
```
If you have added the isActive column, then run the php artisan migrate command to migrate the migration files to the database.
```php
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
];
}
```
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()
```
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
```php
Route::get('/', function () {
return view('welcome',[
'users' => App\Models\User::all()
]);
});
```
In this fourth step, we only need to update the existing route, i.e. add data from the User model.

##Step 5: Setup View
```php
<!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>
```
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
```
In this sixth step, we need to install livewire. To install livewire, we can run the command as above.
```php
...
    @livewireStyles
</head>
<body>
    ...
 
    @livewireScripts
</body>
</html>
```
After installing livewire, add @livewireStyles in the head tag and @livewireScripts before the end of the body tag.
```
php artisan make:livewire UserStatus
```
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
<?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');
    }
}
```
Then, open the UserStatus.php file and change the code to be like the code above.
```php
<div class="form-check form-switch">
  <input class="form-check-input"  wire:model.lazy="isActive" type="checkbox" role="switch" @if($isActive) checked @endif>
</div>
```
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.
```php
<td>TBA<td>
```
Now, open the welcome.blade.php file and look for the code as above, then replace it with the code as below.
```php
<td>
    @livewire('user-status', ['model' => $user, 'field' => 'isActive'], key($user->id))
</td>
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2kkonoxx0qh6dmn2yze4.PNG)
Alright, after going through the step by step to create or use the toggle switch to change the data status in [laravel](https://codelapan.com/tag/laravel) [livewire](https://codelapan.com/tag/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. 🥂