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?
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.