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

RoboRobok's avatar

Is there a new fancy way to query by relationship?

Hey folks, is there some cool Eloquent method to query, let's say, Dogs where Owner's ID is equal 3 or barked_at IS NULL? Silly example, but I'd like to understand how to query for relationship in a fancy way.

I can't use User::find(3)->dogs(), since I also want all dogs that have barked_at IS NULL.

I did this:

$dogs = Dog::whereNull('barked_at')
    ->orWhereRelation('owners', (new User())->getKeyName(), 3)
    ->get();

Is there any nicer way instead of using orWhereRelation in combination with (new User())->getKeyName() in my case?

0 likes
7 replies
martinbean's avatar

Hey folks, is there some cool Eloquent method to query

@roborobok No.

let's say, Dogs where Owner's ID is equal 3 or barked_at IS NULL?

Then just query dogs with those conditions?

$dogs = Dog::query()->whereNull('barked_at')->orWhere('owner_id', '=', 3)->get();
RoboRobok's avatar

@martinbean there's nothing cool about your solution, I wanted to keep column names dynamic per model definition.

martinbean's avatar

@RoboRobok I didn’t say it was cool. I gave you a solution based on the problem statement provided.

yeah, I know that's what average devs do. Thanks.

Stop being a tosser.

8 likes
kevinbui's avatar

You might know that this is possible:

Dog::whereOwnerId(3);

I don't know whether this is gonna work, but you can try this:

Dog::whereNull('barked_at')
    ->orWhereOwnerId(3)
    ->get();

I also read laravel secrets and found out those are possible:

// This is gonna work
Dog::whereBarkedAtAndOwnerId(null, 3)
    ->get();

// You might try this
Dog::whereBarkedAtOrOwnerId(null, 3)
    ->get();

Still, just keep it simple like @martinbean 's answer.

1 like

Please or to participate in this conversation.