Is there a Policy-like before() function available on models that can do a bunch of pre-processing stuff?
Laravel | Conditional search query based on user role / status
Hi, team:
I have a scenario where user records can be pulled up based on requester's "admin" role. Short of writing an if/else query such as below, is there an elegant way to deal with this?
public function search(Request $request) { $this->validateSearchRequest($request);
if (Auth::user()->isSuperAdmin()) {
return User::where('fname', 'like', '%' . $request->search_keywords . '%')
->orWhere('lname', 'like', '%' . $request->search_keywords . '%')
->orderBy('fname')
->limit($this->defaultLimitTo)
->get();
} else {
return User::where('admin_id', Auth::id())
->orWhere('fname', 'like', '%' . $request->search_keywords . '%')
->orWhere('lname', 'like', '%' . $request->search_keywords . '%')
->orderBy('fname')
->limit($this->defaultLimitTo)
->get();
}
}
Notice the additional where clause in the else scenario.
Can a decorator be written that can use isSuperAdmin() status and do conditional things without making the code an if/else mess?
Thank you.
There is also a when method on the query builder which might make this look better!
$query = User::when(!Auth::user()->isSuperAdmin(), function ($query) use ($request) {
return $query->where('admin_id', Auth::id());
})
->orWhere('fname', 'like', '%' . $request->search_keywords . '%');
->orWhere('lname', 'like', '%' . $request->search_keywords . '%')
->orderBy('fname')
->limit($this->defaultLimitTo)
->get();
I think this is it. I didn't tested it!
Documentation: https://laravel.com/docs/5.5/queries#conditional-clauses
Please or to participate in this conversation.