cash's avatar
Level 5

Strange 'find' behavior

When I provide an id for the find method it will return an instance of a model. i.e. Comment::find(1) will return an instance of \App\Models\Comment

But when I provide a model instance to the find method I will get Illuminate\Database\Eloquent\Collection instance.

And this will break the code from the documentation on validation if we've used route model binding because $comment will be a collection and $this->user()->can('update', $comment); will not hit the policy.

use App\Models\Comment;
 
/**
 * Determine if the user is authorized to make this request.
 */
public function authorize(): bool
{
    $comment = Comment::find($this->route('comment'));
 
    return $comment && $this->user()->can('update', $comment);
}

So in my case, when I use route model binding I do it like this:

public function authorize(): bool
{
    return $this->user()->can('update', $this->route('comment'));
}

What are your thoughts about this?

0 likes
1 reply
aleahy's avatar
aleahy
Best Answer
Level 25

If you read a little bit more in that documentation, it mentions that if you use route model binding, it should be

return $this->user()->can('update', $this->comment);

The find method accepts an id, or it accepts an array of ids. If you pass it a model, it will call toArray on the model and use any ids it can find in its values.

1 like

Please or to participate in this conversation.