Level 51
Don't use with, Just do it like $product->category, because it's just belongsTo so you will not run against N + 1 problem.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Let's imagine that we have a product model which belongs to a category, but the category can be null.
Product->with('category')->find(1);
This gives me a product with a category. If category_id is null, the relationship is also null (as expected). But Laravel runs 2 queries:
select * from `products` where `products`.`id` = 1 limit 1
select * from categories where 0 = 1 and categories.deleted_at is null
Is there a native laravel way to avoid the second query when the foreign key is null?
Please or to participate in this conversation.