From 0b23340117b0f00f8d7a99dce19b2c5e35091a4b Mon Sep 17 00:00:00 2001 From: Jyothsna M S Date: Fri, 30 Jan 2026 15:11:42 -0600 Subject: [PATCH] Add findWith and findOrFailWith methods to Eloquent Builder --- Eloquent/Builder.php | 54 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/Eloquent/Builder.php b/Eloquent/Builder.php index fff8e8fe6..31082f876 100755 --- a/Eloquent/Builder.php +++ b/Eloquent/Builder.php @@ -12,6 +12,7 @@ use Illuminate\Database\Eloquent\Concerns\QueriesRelationships; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\Relation; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\RecordsNotFoundException; use Illuminate\Database\UniqueConstraintViolationException; @@ -638,6 +639,59 @@ public function findOrFail($id, $columns = ['*']) return $result; } + /** + * Find a model by its primary key and eager load relations. + * + * @param mixed $id + * @param array $relations + * @param array|string $columns + * @return ($id is (\Illuminate\Contracts\Support\Arrayable|array) + * ? \Illuminate\Database\Eloquent\Collection + * : TModel|null) + */ + public function findWith($id, array $relations = [], $columns = ['*']) + { + return $this->with($relations)->find($id, $columns); + } + + /** + * Find a model by its primary key and eager load relations or throw an exception. + * + * @param mixed $id + * @param array $relations + * @param array|string $columns + * @return ($id is (\Illuminate\Contracts\Support\Arrayable|array) + * ? \Illuminate\Database\Eloquent\Collection + * : TModel) + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function findOrFailWith($id, array $relations = [], $columns = ['*']) + { + $result = $this->findWith($id, $relations, $columns); + + $id = $id instanceof Arrayable ? $id->toArray() : $id; + + if (is_array($id)) { + if (count($result) !== count(array_unique($id))) { + throw (new ModelNotFoundException)->setModel( + get_class($this->model), array_diff($id, $result->modelKeys()) + ); + } + + return $result; + } + + if (is_null($result)) { + throw (new ModelNotFoundException)->setModel( + get_class($this->model), $id + ); + } + + return $result; + } + + /** * Find a model by its primary key or return fresh model instance. *