Home > Mobile >  How to Filter Data By Checkbox Using Livewire Laravel
How to Filter Data By Checkbox Using Livewire Laravel

Time:01-03

I want to make a filter by checking, in this case, I have one Course table and in this table I include Level Field, where the customer can filter the course by level, for example I have levels like Beginner, Intermediate, and soon. So, my problem is I want to display Level start form ALL, BEGINNER, INTERMEDIATE and soon, so how I can make when they click ALL then all data display than when they checked Beginner and Intermediate then the data where has Beginner and Intermediate value display all not one of them. anyone, please help me, I don't have any idea about this. so far this my code come from Livewire/SearchCourse:

public $all,$beginner,$intermediate;

public function render()
{
    return view('livewire.search-course', [
        'courses' => Course::when($this->beginner, function ($query, $term){
            return $query->where('level', 'LIKE', "%$term%");
        })
            ->paginate(10)
    ]);
}

And this is my code on blade for checkbox:

<div >
    <span >{{ __('Skill Level') }}</span>
    <!-- Checkbox -->
    <div >
        <input type="checkbox"  wire:model="all"
               id="level" name="level" value="">
        <label  for="all">All</label>
    </div>
    <div >
        <input type="checkbox"  wire:model="beginner"
               id="level" name="level" value="beginner">
        <label  for="beginner">Beginner</label>
    </div>
    <div >
        <input type="checkbox"  wire:model="intermediate"
               id="level" name="level" value="intermediate">
        <label  for="intermediate">Intemediate</label>
    </div>
</div>

Thank u so much for any help.

CodePudding user response:

You can do something similar to the following with Lifecycle Hooks

public $courses = [];

public $filters = [
    'all' => false,
    'beginner' => false,
    'intermediate' => false,
];

public function updatedFilters()
{

    $result = new Collection();

    if ($this->filters['all']) {

        $result = $result->merge(Course::where('level', 'LIKE', "%all%"));

    } elseif($this->filters['beginner']) {

        $result = $result->merge(Course::where('level', 'LIKE', "           
  • Related