I want to remove the admin user from my collection. I know its the primary key in the table (id) is 1. But when I use forget(1)
it deletes the array element in the collection starting from 0. How do I remove the item from the collection by the id?
// Grab all the users
$users = User::all(); //$this->user; use to return array not Laravel Object
if($users->find(1)->hasRole('admin'))
$users->forget(0);
Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.
unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. If a globalized variable is unset() inside of a function, only the local variable is destroyed.
If your database table has lots of data, chunk() method is the best to use. The chunk() method can be used on the DB facade and also on Eloquent models. The chunk() takes care of fetching a small amount of data at a time and the result is present inside the closure for processing.
As such bencohenbaritone's answer is better way to resolve this problem, I have to add that Laravel Eloquent Collection has method except()
, which can remove Eloquent objects from the collection by primary key instead of forget()
. The latter one removes by collection index key (like array[i]
) and not by primary key.
So you can write something like (sorry about the bad example, my own use case is too different to be useful for others):
$admin_user_id = 20;
$users = User::all();
$users_without_admin = $users->except($admin_user_id);
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