Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.5 find($id) returns collection instead of single object

Tags:

laravel

Laravel 5.5 find($id) returns collection instead of single object

Any idea why, and how to prevent this? I'm having to use ->first() as workaround

public function destroy(client $client)
    {

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

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

        return redirect('/clients');

    }
like image 732
Mike Thrussell Avatar asked Sep 08 '17 13:09

Mike Thrussell


2 Answers

find() and findOrFail() need an integer to return one element. If you pass something else, you will get a collection.

Since you are asking for a Client object as a parameter, you don't have to check it. Laravel will never fire this function when the object does not exists, so you don't have to check it.

public function destroy(Client $client)
{

    $client->delete();

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

    return redirect('/clients');

}

For more information read https://laravel.com/docs/5.5/eloquent#retrieving-single-models and the following part with not found exception

like image 52
cre8 Avatar answered Nov 15 '22 17:11

cre8


$client is already an instance of Client as you typehint it. You shouldn't need to "find" it again. Checking if it exists and then run delete should be enough.

public function destroy(client $client)
{

    if ($client->exists)
        $client->delete();

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

    return redirect('/clients');

}
like image 1
Marwelln Avatar answered Nov 15 '22 19:11

Marwelln