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?
// 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
You can find it in vendor\laravel\framework\scr\Illuminate\Database\Eloquent\Builder.php on line number 112
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.
You should see the autocomplete for that function in PHPStorm, sure you imported the model and have autocomplete on?
@bashy , yes, the model is imported correctly.
The problem only occours with findOrFail() and not with find.
Reading the entire Model class, the "problem" seens to be because this method is called by an magic method call.
I use the https://github.com/barryvdh/laravel-ide-helper but it don't solve this problem.
Actually, that's true. I was looking at failOrNew
i have the same problem...help please
PHPStorm does not identify what Model ::findOrFail
Please sign in or create an account to participate in this conversation.