Reputation: 2283
I'm experiencing difficulty in writing this query in laravel 5.1,
select * from `host_requests` where `host_id` = 5 and (`email` LIKE "%v%" or `request_url` LIKE "%v%")
The purpose of this query is to fetch records that are associated with host_id = 5, also email and request_url are optional if they set then LIKE clause should be used. I wrote the query in laravel like this
$searchname = "v";
$hostid = "5";
$data = HostRequest::where('email', 'LIKE', '%' . $searchname . '%')
->where('host_id', $hostid)
->orwhere('request_url', 'LIKE', '%' . $searchname . '%')
->latest('id')
->paginate($size);
It is fetching all the records that are also not associated with host_id = 5.
Any help is much appreciated..Thanks
Upvotes: 2
Views: 71
Reputation: 163748
You should use where()
with closure like this:
$data = HostRequest::where('host_id', $hostid)
->where(function($q) use($searchname) {
$q->where('email', 'like', '%'.$searchname.'%')
->orWhere('request_url', 'like', '%'.$searchname.'%');
})->orderBy('id', 'desc')
->paginate($size);
Upvotes: 4
Reputation: 53
Try this code:
$data = HostRequest::where(function ($query) use ($searchname) {
$query->orwhere('email', 'like', '%'.$searchname.'%')
->orWhere('request_url', 'like', '%'.$searchname.'%');
})
->where('host_id', $hostid)
->latest('host_id')
->paginate($size);
Upvotes: 0