Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top