This is for Laravel 5.2. I have a method defined as follows in my Users model:
public function name()
{
return "$this->name_first $this->name_last";
}
I'm trying to figure out how to use that as part of a query, but it seems like it isn't possible for a somewhat obvious reason: the database doesn't know anything about the method and that makes perfect sense. However, the concept of what I'm trying to achieve makes sense in certain contexts, so I'm trying to see if there's a way to accomplish it naturally in Eloquent.
This doesn't work, but it represents what I'm trying to accomplish:
public function index(Request $request)
{
$query = new User();
if(Request::has('name')) {
$query = $query->where('name', 'LIKE', '%' . Request::input('name') . '%');
}
return $query->get();
}
In short, the database only knows about name_first
and name_last
, but I'd like to be able to search (and sort) on name
without storing it. Maybe storing the concatenated name is no big deal and I should just do it, but I'm also trying to learn.
I agree with Bogdan, The issue of having spaces either in the first or the last name makes querying on the individual columns difficult, so this is probably the way to go. Code reuse can be increased by defining it as a custom scope: https://laravel.com/docs/5.2/eloquent#local-scopes
// class User
public function scopeOfFullNameLike($query, $fullName)
{
return $query->whereRaw('CONCAT(name_first, " ", name_last) LIKE "%?%"', [$fullName]);
}
// ...
User::ofFullNameLike('john doe')->get();
That would mean you should be concatenating the column value at the database level. Which means you could use CONCAT
and a whereRaw
clause:
$query->whereRaw('CONCAT(name_first, " ", name_last) LIKE ?', ['%' . Request::input('name') . '%']);
Or as an alternative if you want the full name to be selected as part of the result, you could concatenate within the select and use having
instead of where
to be able to use a column alias:
$query->select('*', DB::raw('CONCAT(name_first, " ", name_last) as name'))
->having('name', 'LIKE', '%' . Request::input('name') . '%');
Not the most compact solutions, but things involving MySQL functions need some raw SQL to work with the Query Builder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With