mpen
mpen

Reputation: 283103

Laravel get/map with key

I was hoping I could do this on one line:

$users = [];
$rawUsers = User::select('id','first_name','last_name')->where('company_id',Auth::user()->company_id)->get();
foreach($rawUsers as $u) {
    $users[$u['id']] = $u['first_name'].' '.$u['last_name'];
}

I see the Collection class has a ->map function which would let me do the concatenation, but I don't know how to get the results indexed by id. Is there a way to do what I want?

Upvotes: 1

Views: 2918

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

You can do this using lists method on the query:

User::select(DB::raw('concat(first_name," ",last_name) as full_name'), 'id')->lists('full_name', 'id');
// returns array(id => full_name, ...)

Or use accessor on the model and lists on the collection:

// User model
public function getFullNameAttribute()
{
    return $this->attributes['first_name'].' '.$this->attributes['last_name'];
}

// then on the collection call lists:
$usersRaw = User::where(...)->get()->lists('fullName','id');

Upvotes: 4

Related Questions