Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent add 'where' clause in the query by condition

Tags:

laravel

I want to add a condition first before adding another where query it but seems that laravel won't allow. I want something like the following.

function index()
{
    $role = Auth::user()->role; //SEE_ALL, SEE_DEPT_A, SEE_DEPT_B

    $q = Input::get('q');
    if ($q != "") {
        $user = User::where('name', 'LIKE', '%' . $q . '%')
            ->orWhere('email', 'LIKE', '%' . $q . '%')
            ->orderBy('name');

        if ($role == "SEE_DEPT_A") {
            $user->where('user_department', "A");
        }

        $user->paginate(10)->appends('q', $q);
    }

    return view('users.index')->with('data', ['users' => $user, 'q' => $q]);
}
like image 982
beginner Avatar asked Oct 29 '25 16:10

beginner


1 Answers

You should use the when() function :

$user = User::where('name', 'LIKE', '%' . $q . '%')
            ->orWhere('email', 'LIKE', '%' . $q . '%')
            ->orderBy('name')

        ->when($role == "SEE_DEPT_A", function($query){
             return $query->where('user_department', "A");
        })->paginate(10)->appends('q', $q);
like image 173
Mathieu Ferre Avatar answered Oct 31 '25 06:10

Mathieu Ferre