Laravel Eloquent gotcha using With and Find

The Eloquent ORM in Laravel makes it easy to pull in related models using the ::with() method.  It’s very useful and can solve the N+1 Query problem that can occur when accessing related models in a loop from the parents records.

<?php
$data = MyParentModel->with('ChildModel');

You’d commonly want to use this when accessing a particular parent model using the ::find() or ::findOrFail() method. The trap can be that with() must be called before findOrFail().

If you chain methods and call findOrFail() first it will be ignored and your result set will include all parent rows!

<?php
$data = MyParentModel->with('ChildModel')->findOrFail($parent_id);

Leave a Reply

Your email address will not be published. Required fields are marked *