Phil
Phil

Reputation: 2236

Laravel: how to remove item from Collection by id

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);

Upvotes: 17

Views: 35956

Answers (2)

trm42
trm42

Reputation: 2676

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);

Upvotes: 27

bthecohen
bthecohen

Reputation: 486

Instead of trying to delete an item from the collection, it would be better to never select it in the first place.

You could add a constraint to your DB query like this:

$users = User::where('role', '!=', 'admin')->get();

(It could be slightly different depending on how roles are defined in your schema).

If you are using a more complex schema with a separate roles table and user_role table, you can query like this:

$users = User::whereHas('roles', function($q){
    $q->where('role', '!=', 'admin');
})->get();

It's a bad idea to rely on the admin user always being the first item in the collection. What if later you want to have multiple admin users, or to sort the user list by registration date? If you really want to remove admin from the collection, Eloquent has built-in filtering functionality:

$usersWithoutAdmins = $users->filter(function($user)
{
    return !$user->hasRole('admin');
});

Upvotes: 18

Related Questions