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

Rediska's avatar

How to add an "if" condition to a query?

Could you tell me, please, is it possible to add an "if" condition to the query? I have a request:

 public static function getAllAvailableAttributes ($categoryTitle, $attrBrand, $attrColor) {
        return static::select(['brand', 'color', 'size'])
		->where([
				['stock', 'in-stock'],
				['brand', '!=', ''],
				['color', '!=', ''],
			])
		->where(function ($query) use ($categoryTitle) {
                foreach ($categoryTitle as $item) {
                    $query->orWhere('category_title', $item);
                }
            })
		->where(function ($query) use ($attrBrand) {
                foreach ($attrBrand as $id => $item) {
                    $query->orWhere('brand', $item->title);
                }
            })
		->where(function ($query) use ($attrColor) {
                foreach ($attrColoras $id => $item) {
                    $query->orWhere('color', $item->title);
                }
            })
		->get();

But the problem is that $attrBrand and $attrColor values do not always come. Sometimes they are null. how can I check if the value is null or not before running the condition? This method is certainly not correct, but for clarity, I will show what I need:

if($attrColor != null) {
->where(function ($query) use ($attrColor) {
                foreach ($attrColoras $id => $item) {
                    $query->orWhere('color', $item->title);
                }
            })
}
0 likes
13 replies
Rediska's avatar

@tykus

->where(function ($query) use ($attrColor) {
                if ($attrColor!= null) {
                    foreach ($attrColoras $id => $item) {
                        $query->orWhere('color', $item->title);
                    }
                }
            })

Can it be done this way? I did and it seems to have worked.

tykus's avatar

@Rediska what is $attrVozrast - it is not even in scope?

Edit: you changed it... so if $attrColor is an array; an empty array, then even the if block is unnecessary.

tykus's avatar

@Rediska you don't need the if block if you ensure the $attrColor variable defaults to an empty array.

 public static function getAllAvailableAttributes ($categoryTitle, $attrBrand, $attrColor = []) {
1 like
Rediska's avatar

@tykus I tried to follow your example and got an error: ErrorException Invalid argument supplied for foreach()

Default value is always null

Rediska's avatar

@tykus Yes, I made a mistake. If you fix it to [], then everything works correctly! This is about me =) Thank you all!

Snapey's avatar

Note that all your where statements are AND conditions. Is this what you intended?

Rediska's avatar

@Snapey I'm still trying to figure out the product filter. I determine from the URL which filters were requested. And in order not to display empty attributes, I'm trying to make such a check =)))

Snapey's avatar
Snapey
Best Answer
Level 122

You can do it like this

        $query = static::select(['brand', 'color', 'size'])
		->where([
				['stock', 'in-stock'],
				['brand', '!=', ''],
				['color', '!=', ''],
			]);

        if($request->categoryTitle)->filled()) {
		  $query->where(function ($query) use ($categoryTitle) {
                foreach ($categoryTitle as $item) {
                    $query->orWhere('category_title', $item);
                }
            });

        if($request->attrBrand)->filled()) {
		  $query->where(function ($query) use ($attrBrand) {
                foreach ($attrBrand as $id => $item) {
                    $query->orWhere('brand', $item->title);
                }
            });

        if($request->attrColor)->filled()) {
		  $query->where(function ($query) use ($attrColor) {
                foreach ($attrColor as $id => $item) {
                    $query->orWhere('color', $item->title);
                }
            })
		
	return $query->get();

So, building up the query if filters are set.

What @tykus is saying is that there is a when method that does the same but allows it to be constructed as one fluent eloquent statement;

        return static::select(['brand', 'color', 'size'])
		->where([
				['stock', 'in-stock'],
				['brand', '!=', ''],
				['color', '!=', ''],
			])
        ->when($request->categoryTitle)->filled()) {
		  $query->where(function ($query) use ($categoryTitle) {
                foreach ($categoryTitle as $item) {
                    $query->orWhere('category_title', $item);
                }
            })
		->when($request->attrBrand)->filled()) {
		  $query->where(function ($query) use ($attrBrand) {
                foreach ($attrBrand as $id => $item) {
                    $query->orWhere('brand', $item->title);
                }
            })
        ->when($request->attrColor)->filled()) {
		  $query->where(function ($query) use ($attrColor) {
                foreach ($attrColor as $id => $item) {
                    $query->orWhere('color', $item->title);
                }
            })
            ->get()
		

Note I notice your filters look off? item on category and item->name on the others? What does your form return as filters? Surely just an array of selected filters or checkboxes?

2 likes
Rediska's avatar

@Snapey Thank you very much! I'll figure it out now.

P.S. And don't laugh at my code =))) I know he's very scary. But someday I will become as smart as you =) Here I will gain experience and will also answer questions on the forum =)

Please or to participate in this conversation.