This is a simple example of my situation:
There is a model User
that hasOne UserInfo
.
I want to retrieve a User via (where) different UserInfo columns, but I don't want all the wheres to be chained and specifically I don't want the ->get()
being chained at the end of where clauses.
All solutions examples and documentation I've read lead to an endless where chaining ending with a ->get()
. For some reason whereHas
also stops working when I move the get to a next line. Maybe my syntax is wrong.
I prefer using Eloquent but if something like that can be achieved only by using the DB class I wont mind.
Expample (simplified but that's the most of it):
$applicant = User::whereHas('UserInfo', function($query) use ($request) {
$query->where('gender', $request->gender);
})->get();
This works perfectly. However (except of being a weird bloat of code for a single where
, when relationship in other cases are so powerful) I want to remove the User::
and the ->get();
from there. Meaning looking to achieve something like this:
$user = new User;
$user->whereHas('UserInfo', function($query) use ($request) {
return $query->where('gender', $request->gender);
});
return $user->get();
And for whoever wants to read more code here's the full snippet
$user = new User;
if(! empty($request->gender))
{
$user->whereHas('UserInfo', function($query) use ($request) {
$query->where('gender', $request->gender);
});
}
if(! empty($request->role_id))
{
$user->whereHas('UserInfo', function($query) use ($request) {
$query->where('role_id', $request->role_id);
});
}
$applicant = $user->get();