Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shimana's avatar

Better use of Query Builder

I'm using Livewire, I want to filter the images,And I want to display the images in two ways based on the radio button,One based on user uploaded images and the other based on category

    public function render()
    {
        $images = Gallery::query()
            ->when($this->selectedStatus, function ($query) {
                return $query->where('category', $this->selectedStatus);
            })
            ->when($this->selectedStatus == "1", function ($query) {
                return $query->where('user_id', auth()->id());
            })
            ->orderBy('created_at', 'DESC')->paginate($this->perPage);
        return view('livewire.dashboard.images', compact('images'));
    }

I use this code but it does not show the uploaded images of the user,

So I had to test the code like this and it showed me the correct output.

    public function render()
    {
        if ($this->selectedStatus == 1) {
            $images = Gallery::query()
                ->when($this->selectedStatus == "1", function ($query) {
                    return $query->where('user_id', auth()->id());
                })->orderBy('created_at', 'DESC')->paginate($this->perPage);
        } else {
            $images = Gallery::query()
                ->when($this->selectedStatus, function ($query) {
                    return $query->where('category', $this->selectedStatus);
                })->orderBy('created_at', 'DESC')->paginate($this->perPage);

        }
        return view('livewire.dashboard.images', compact('images'));
    }

But I'm not sure if this is the right way to go. please guide me

0 likes
2 replies
MichalOravec's avatar
Level 75
$images = Gallery::query()
    ->when($this->selectedStatus, function ($query, $status) {
        $query->when($status == '1', function ($query) {
            $query->where('user_id', auth()->id());
        }, function ($query) use ($status) {
            $query->where('category', $status);
        });
    })->orderByDesc('created_at')
    ->paginate($this->perPage);
1 like

Please or to participate in this conversation.