Reputation: 2032
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
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
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
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