Eloquent WHERE LIKE clause with multiple columns

一笑奈何 提交于 2020-01-14 04:55:40

问题


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?


回答1:


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!




回答2:


$query = User::where('id', '=', '2');

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

Try this way..



来源:https://stackoverflow.com/questions/42121065/eloquent-where-like-clause-with-multiple-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!