beginner
beginner

Reputation: 2032

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

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]);
}

Upvotes: 4

Views: 8604

Answers (3)

bluestar0505
bluestar0505

Reputation: 701

You can insert multi conditions like this:

$user_model = User::where('name', 'LIKE', '%' . $q . '%')
                    ->orWhere('email', 'LIKE', '%' . $q . '%')
                    ->orderBy('name');
if ($role == "SEE_DEPT_A") {
   $user_model = $user_model->where('user_department', "A");
}
...
//other if statements
...
$users = $user_model->paginate(10)->appends('q', $q);

Upvotes: -2

Mathieu Ferre
Mathieu Ferre

Reputation: 4412

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);

Upvotes: 12

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

You need to assign the statement where you used where clause:

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

And if the if statement does not run (in case of false), it will throw an error about $user being undefined

Upvotes: 2

Related Questions