How to build conditional eloquent query with data which comes from database
I want to create conditional query with data which comes from database. Now im using query and filtering method but i wonder is there any method to build query for this?
Example: I have a table which exists 2 columns -> user_id and view_preference if view_preference is 0 i want to select all records. But if its 1 i just want to select only matching user_id rows.
Current Working Code:
You want something like this then.
WHERE view_preference = 0
OR (
view_preference = 1
AND (
owner_id = ?
OR supervisor_id = ?
)
)
Appending this to your query builder (before calling get()
) should give you the results you want.
->where('view_preference', 0)
->orWhere(function ($or) use ($request) {
$or->where('view_preference', 1)
->where(function ($and) use ($request) {
$and->where('owner_id', $request->user()->id)
->orWhere('supervisor_id', $request->user()->id);
});
})