EliasSoares's avatar

How does `findOrFail` works behind the scenes?

Hi,

I'm looking for how does findOrFail() method works, but when I seek for ir, I don't find the method implementation.

Can anyone explain me how does Laravel "solve" this?

0 likes
8 replies
sukonovs's avatar
Level 6
// Eloquent/Builder.php
/**
     * Find a model by its primary key or throw an exception.
     *
     * @param  mixed  $id
     * @param  array  $columns
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection
     *
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    public function findOrFail($id, $columns = array('*'))
    {
        $result = $this->find($id, $columns);

        if (is_array($id))
        {
            if (count($result) == count(array_unique($id))) return $result;
        }
        elseif ( ! is_null($result))
        {
            return $result;
        }

        throw (new ModelNotFoundException)->setModel(get_class($this->model));
    }

BTW: This package helps a lot when you need to look under the hood: https://github.com/barryvdh/laravel-ide-helper

bobbybouwmann's avatar

You can find it in vendor\laravel\framework\scr\Illuminate\Database\Eloquent\Builder.php on line number 112

1 like
EliasSoares's avatar

Yes, I've found it right now.

I was looking for this after realize that PHPStorm does not identify what Model::findOrFail returns, causing many wrong warnings on my code.

bashy's avatar

You should see the autocomplete for that function in PHPStorm, sure you imported the model and have autocomplete on?

bashy's avatar

Actually, that's true. I was looking at failOrNew

1 like
Tonyxhepa's avatar

PHPStorm does not identify what Model ::findOrFail

Please or to participate in this conversation.