Laravel 5.5 find($ id)返回集合而不是单个对象

Mik*_*ell 7 laravel

Laravel 5.5 find($ id)返回集合而不是单个对象

知道为什么,以及如何防止这种情况?我不得不使用->first()解决方法

public function destroy(client $client)
    {

        $item = Client::findOrFail($client)->first();
        $item->delete();

        session()->flash('message', 'Client deleted');

        return redirect('/clients');

    }
Run Code Online (Sandbox Code Playgroud)

cre*_*re8 13

find()findOrFail()需要一个整数来返回一个元素.如果您传递其他内容,您将获得一个集合.

由于您要求将Client对象作为参数,因此您无需进行检查.当对象不存在时,Laravel永远不会触发此函数,因此您无需检查它.

public function destroy(Client $client)
{

    $client->delete();

    session()->flash('message', 'Client deleted');

    return redirect('/clients');

}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请阅读https://laravel.com/docs/5.5/eloquent#retrieving-single-models以及以下部分:not found exception

  • “如果你传递了其他东西,你就会得到一个收藏品。” 这对我很有帮助。我以为我传递的是一个整数,但经过仔细检查,你是对的。 (2认同)