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

shimana's avatar

Modify a query code

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->selected, function ($query, $selected) {
                $query->when($selected == '1', function ($query) {
                    $query->where('user_id', auth()->id());
                }
                ,function ($query) use ($selected) {
                    $query->where('category', $selected);
                });
            })->orderByDesc('created_at')
            ->paginate($this->perPage);
        return view('livewire.dashboard.add-image', compact('images'));
    }

in blade:

<select wire:model="selected">
    <option value="">Any</option>
    <option value="1">for user</option>
    <option value="2">portraits</option>
    <option value="3">coral</option>
</select>

The problem is that when I click on (Any), images uploaded by other users are also displayed. Note: I want to display only images recorded by user ID 1 by clicking on (Any ).

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

When has a second parameter

public function render()
    {
        $images = Gallery::query()
            ->when($this->selected, function ($query, $selected) {
                $query->when($selected == '1', function ($query) {
                    $query->where('user_id', auth()->id());
                }
                ,function ($query) use ($selected) {
                    $query->where('category', $selected);
                });
            }, function ($query) {
            $query->where('user_id', 1);
       } )->orderByDesc('created_at')
            ->paginate($this->perPage);
        return view('livewire.dashboard.add-image', compact('images'));
    } 
1 like

Please or to participate in this conversation.