Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: how to remove item from Collection by id

Tags:

php

laravel

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);
like image 581
Phil Avatar asked Jan 21 '15 22:01

Phil


People also ask

What is pluck in laravel?

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.

What is unset in laravel?

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.

What is chunk in laravel?

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.


1 Answers

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);
like image 87
trm42 Avatar answered Sep 17 '22 09:09

trm42