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

ahmeda's avatar

Check if the relation is empty or not within the query?

I have this structure;

products table;
name - .... - brand_id(null)

brands table:
name - visible - ....

The relation of brand in Product model in belongsTo

My query:

$products = Product::whereHas('brand', function ($query) {
                   $query->where('visible',false);
                })
                ->where('special',false)
                ->paginate($this->paginate);

This query worked if brand_id is not null !

How can I check if the brand_id is null it's OK get the products & ignore the relation but if not null check if its brand is visible or not?

0 likes
1 reply
Snapey's avatar
Snapey
Best Answer
Level 122
$products = Product::where(function(query){
        whereHas('brand', function ($query) {
                   $query->where('visible',false);
                })
        ->orwhere('product_id',null);	
    })->where('special',false)
    ->paginate($this->paginate);

Please or to participate in this conversation.