Vahag Chakhoyan
Vahag Chakhoyan

Reputation: 779

How to remove item from laravel query result and get it?

In Laravel project I am making a database query

$addresses = DB::table('residences')->where('user_id', '=', Auth::user()->id)->get();

I want to get one address from that query result, if it exists, where 'id' field equals to 10 for example. But I want to remove that address from $addresses query result simultaneously. Is there a simple way to do that?

Upvotes: 2

Views: 1083

Answers (1)

dparoli
dparoli

Reputation: 9171

You can use the reject() method on the $addresses collection, i.e:

$my_result = false;
$addresses = $addresses->reject(function ($value, $key) use (&$my_result) {
    if($value->id == 10){
        $my_result = $value;
        return true
    }
    return false;
});

Upvotes: 1

Related Questions