I added a full_name
field to User
model like this:
protected $appends = ['full_name'];
public function getFullNameAttribute()
{
return $this->name . ' ' . $this->family;
}
On the other hand I want to select and return specific columns along with full_name field like this:
return User::all('user_id', 'username', 'full_name')
But laravel gets this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'full_name' in 'field list' (SQL: select
user_id
,username
,name
,family
,full_name
fromusers
whereusers
.deleted_at
is null)
How can I do what I want?
I think you don't need to specify that in your select column.. it's already attached with your result set.
If you want specific columns, than you need to probably user $hidden attributes and make them visible whenever you want.
You can't use append attribute in query.
the full_name
only can be access after query.. bcoz full_name is not attach with the result
$users = User::all();
return $users[0]->full_name; //this requred getFullNameAttribute like above
If you still want to do with query. Do in DB query instead.. this no need to $append attribute. full_name already attach with the result
return User::select('user_id', 'username' , DB::raw('CONCAT(name, " ", family) AS full_name'))->get();
Hello you can get two or more column value concated using query like this,
return $user = User::select('user_id', 'username',DB::raw("CONCAT('first_name', " ",'last_name') AS full_name" 'full_name');
Or if you want to concat column from retrieved array you can do like this,
$user = User::all();
foreach($user as $single){
$user->full_name = $single->first_name ." ".$single->last_name
}
print_r($user);
happy coding.