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

Wakanda's avatar
Level 10

Conditional search query

Hi Devs,

I have a live wire class that is supposed to get all the books at first render and then conditional query depending on user input for example if a user clicks on a certain category it returns a book that related to the category. So my question is how can I render my component with books without queries and when needed I serve the user with requested data?

 	public $typeId;
    public $categoryId;
    public $subCategoryId;

    public function render()
    {
        $books = Book::where('book_type_id', $this->typeId)
                        ->where('book_category_id', $this->categoryId)
                        ->where('book_sub_category_id', $this->subCategoryId)
                        ->paginate(12);
	}
0 likes
4 replies
tykus's avatar
tykus
Best Answer
Level 104

You can conditionally constrain the query using the when Builder method whenever the first param is truthy:

public function render()
{
	$books = Book::where('book_type_id', $this->typeId)
		->when($this->categoryId, fn ($builder) => $builder->where('book_category_id', $this->categoryId))
		->when($this->subCategoryId, fn ($builder) => $builder->where('book_sub_category_id', $this->subCategoryId))
		->paginate(12);
	}
1 like
tisuchi's avatar

@wakanda Just to fix the typo on @tykus comment.

It should be -

->when($this->categoryId

instead of -

->when($this->$categoryId
1 like

Please or to participate in this conversation.