0

I am building a dynamic query in eloquent. i matching patterns if pattern doesnt match then i want WHERE 1. Basically my question is how to write WHERE 1 in eloquent

if (preg_match('/pattern/', $request->input('user_search'))) {

  $filter="'email','{$request->input('user_search')}'";

} elseif (preg_match('/pattern/', $request->input('user_search'))) {
  
  $filter="'mobile','{$request->input('user_search')}'";

} elseif (preg_match('/pattern/', $request->input('user_search'))) {
  
  $filter="'name','like','%{$request->input('user_search')}%'";

} else {
  $filter=' I want WHERE 1 here';
  The question how to write WHERE 1
}

$user = User::where($filter)->orderBy('created_at', 'DESC')->paginate(50);
2
  • why do you need WHERE 1? and what version of Laravel and PHP are you using? also all those "filters" are strings, the where method works on columns and values Commented Nov 28, 2020 at 13:36
  • I want if no conditions matches then its return all record Commented Nov 28, 2020 at 13:38

1 Answer 1

1

Since you want to define what is passed to where in one statement and not using multiple variables for the arguments, you can use an array:

if (preg_match('/pattern/', $request->input('user_search'))) {
    $filter = [['email', $request->input('user_search')]];
} elseif (preg_match('/pattern/', $request->input('user_search'))) {
    $filter = [['mobile', $request->input('user_search')]];
} elseif (preg_match('/pattern/', $request->input('user_search'))) {
    $filter = [['name', 'like', '%'. $request->input('user_search') .'%']];
} else {
    $filter = [];
}

$users = User::where($filter)->orderBy('created_at', 'DESC')->paginate(50);

If you pass an empty array to where it does not add a WHERE condition.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.