1

In Laravel 4 I have built a search form. Where a person can submit either

email address From - To date Ref number

They can only search using one of the above options; As they have to select from a drop down on which they would like to search with. The final code I used to get this working is as follows:

if(Input::get('from') && Input::get('to')){
            $records = Applications::where('created_at', '>=', Input::get('from'))
                ->where('created_at', '<', date('Y-m-d', strtotime(Input::get('to'). ' + 1 days')))
                ->lists('id');
    }elseif(Input::get('email') || Input::get('ref')){
        $records = Applications::where('Application_number', '=', Input::get('ref'))
            ->where('email', '=', Input::get('email'), 'OR')
            ->lists('id');
    }else{
        $records = Applications::all()->lists('id');
    }

The works for my requirements, but I'm not really happy this is the best solution.

I also tried to use either of the solutions in this thread Laravel 4 eloquent WHERE with OR AND OR?

$result = User::where('created_at', 'LIKE', '%' . $search . '%')
    ->where('updated_at', 'LIKE', '%' . $search . '%', 'OR')
    ->where('user_first_name', 'LIKE', '%' . $search . '%', 'AND')
    ->where('user_any_field', 'LIKE', '%' . $search . '%')->get();

OR

    Model::where(function ($query) {
    $query->where('a', '=', 1)
          ->orWhere('b', '=', 1);
})->where(function ($query) {
    $query->where('c', '=', 1)
          ->orWhere('d', '=', 1);
});

But all I kept getting was value can't be null, when searching on from and to; email and ref worked fine.

2
  • I didn't get your question, sorry. Did you manage to make it work and want a better solution, or there is some error ? Commented May 10, 2014 at 8:42
  • Hi Faust, apologies I've been away for a bit and thought I'd get an email notification when a response was added :-( So I didn't get it working with the first code snippet. But yes was looking for a better way to complete the solution as the two following snippets I feel should work but didn't in my situation and think that would offer a better solution Commented Jun 24, 2014 at 22:44

1 Answer 1

4

You can try this:

$input = Input::all();

Model::where(function($query) use ($input) {
     if (isset($input['something'])) {
         $query->where('some_field_1', '=', $input['something']);
     }

     if (isset($input['something_else'])) {
         $query->where('some_field_2', '=', $input['something_else']);
     }
})->get();

I think this is the cleanest way. Of course, you should put the if statements to be of your need.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.