Skip to main content

Categories Table - Toggle Active

Premium
3 min read

You probably have noticed that we have "Active" toggle in the table. Let's implement its behavior, so you could click on that Toggle to change the value immediately, without leaving the table page.

This is the expected result, visually:

Better toggle button

You might have seen that in Categories migration we have a column is_active, so we will change its value in the database.

First, we need a public property in the Livewire Component. It will be an array and called $active...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 46 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

RB
Rajesh Budhathoki ✓ Link copied!

How can we apply a newer @checked blade directive?

PK
Povilas Korop ✓ Link copied!

I don't think we can apply it here.

RA
Richard A. Hoyle ✓ Link copied!

Getting Error

Attempt to read property "index" on null

I thank something is missing, but What, and where should it be?

A
augusto-dmh ✓ Link copied!

Why are we creating an in-memory dictionary (an associative array with same structure for all key-value pairs) to hold the value from each category's is_active property?

Couldn't we just bind the toggling to the is_active of the current iterated $category inside the loop?

I did that and got the same result, with more performance and readability: the active array does not need to be recreated on every update in $categories; the toggleIsActive receives as argument the $category itself rather than its id (thus no need to fetch it in the database: we just update it directly).

e.g:

public function activeToggle(Category $category)
{
$category->update(['is_active' => !$category->is_active]);
}
<input
type="checkbox"
id="is-active-{{ $category->id }}"
wire:key="is-active-{{ $category->id }}"
wire:click="activeToggle({{ $category }})"
wire:loading.attr="disabled"
{{ $category->is_active ? 'checked' : '' }}
class="sr-only peer"/>

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.