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

JackJones's avatar

Do not query if primary key field is empty

I'm using eager loading, and a lot of the time the primary key id is null

Eloquent is still running the query for the null values:

select * from `continents` where `continents`.`id` in ('1', '3')
select * from `countries` where `countries`.`id` in ('')
select * from `dependencies` where `dependencies`.`id` in ('')
select * from `macro_regions` where `macro_regions`.`id` in ('')

The last 3 queries are useless, but eloquent should know that really, is there any way around it to say "if all the values are null, don't bother with the query"?

0 likes
10 replies
rawilk's avatar

That's really up to you. If you show your queries, we might be able to actually help you.

Snapey's avatar

Are your fk fields null? What is the default value for them?

JackJones's avatar
        $query = Place::whereIn('type_1', $this->places->parentTypes($place->type_1))
            ->with(['continent', 'country', 'dependency', 'macro_region'])
            ->approved()
            ->limit(10);

It's just eager loading basic relationships

JackJones's avatar

The default for the foreign key is null, but the foreign key is within the table itself, i.e. the continent_id is equal to an id in the same table

Basically I want to tell Eloquent if that field is null, don't bother trying to look for a value

JackJones's avatar

I think a $foreign variable on the Model could potentially be the way forward, because obviously in some instances such as TEXT types or VARCHAR you may want to search on empty strings

Thanks for your help, I tried googling but my skills obviously aren't as good as yours

I'll keep my fingers crossed for 5.8

shez1983's avatar

its quite silly that this was discussed in few different laravel areas but ultimately shot down even when taylor said to do a PR.. :s silly

Snapey's avatar

Not as elegant, but this does eager loading but avoids the empty query

    $post = \App\Post::find(1);
    if($post->user_id) $post->load('user'); 

shez1983's avatar

i saw someone doing it in the actual relationship function.. so your code is not littered with all these ifs.. and also the withDefault()

Please or to participate in this conversation.