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');
}
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
$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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With