Eloquent WHERE LIKE clause with multiple columns

2020-07-22 09:51发布

I'm implementing a search bar that can search customers by first name, last name, or both. So, for example, Mike Hizer would be matched by Mike, Hizer, zer, Mike Hizer, etc. Here's what I came up with:

Customer::where(
    DB::raw('concat(first_name," ",last_name)'), 'like', "%{$request->search}%"
)->get()

It works. But is there a more Eloquent approach to combine these two columns (first_name and last_name) without resorting to the DB facade? Would something like

->where(['first_name','last_name'], 'like', "%{$request->search}%")

be possible to achieve?

2条回答
家丑人穷心不美
2楼-- · 2020-07-22 10:35
$query = User::where('id', '=', '2');

$query->where('first_name', 'LIKE', "%$search%");
$query->or_where('last_name', 'LIKE', "%$search%");
$users = $query->get();

Try this way..

查看更多
神经病院院长
3楼-- · 2020-07-22 10:39

If you don't want to use the DB facade you could use the whereRaw method:

Customer::whereRaw('concat(first_name," ",last_name) like ?', "%{$request->search}%")->get();

Hope this helps!

查看更多
登录 后发表回答