Greetings,
I am trying to do a search on an appended attribute, or to add it to the Eloquent model.
For example: Supose i have my User model with a first_name and a last_name column, and i'm appending a name attribute that concatenates both so i won't have to do $user->first_name . ' ' . $user->last_name
every time on my view.
So i set up my accessor:
/**
* Get full name
* @return string
*/
public function getNameAttribute(){
return $this->first_name . ' ' . $this->last_name;
}
And my appended property:
protected $appends = ['name']
and i can call it perfectly on the view as $user->name
But it also would be nice to query that appended attribute.
$query->where('name', 'like', '%' . $request->term . '%');
I know the easy way out:
$query->where('first_name', 'like', '%' . $request->term . '%') ->where('last_name', 'like', '%' . $request->term . '%');
But i am really looking to query the appended attribute. It won't let me query the 'name' appended attribute, because obviously it says column not found. And i don't want to create a column just for that since it's redundant.
I know that $appends only works for arrays or jsons, but i would like to add it to the Eloquent Model like a virtual field so i can query it.
App\User::first()
=> App\User {#892
...
first_name: "Test",
last_name: "Admin",
email: "[email protected]",
...
// I WANT MY NAME HERE :(
}
App\User::first()->toArray()
[
...
"first_name" => "Test",
"last_name" => "Admin",
"email" => "[email protected]",
...
"name" => "Test Admin",
]
Any help would be appreciated.
I didn't found this on forums, neither on the How do I? series.