Поиск с использованием выпадающих опций с дополнительной фильтрацией - Laravel 5.7 - PullRequest
0 голосов
/ 09 ноября 2018

Я хочу добавить опцию, когда в раскрывающемся списке выбраны «рекомендация» или «источник», чтобы получить всех кандидатов, имеющих в одном из этих двух столбцов что-то отличное от нуля или «0», и отсортировать их, используя «create_at» , с сегодняшнего дня.

Это мой взгляд:

    <div class="container">
<div class="row">
<div class="col-lg-12 col-md-12">
    <form class="search-form search-form-basic" action="/candidates/index" method="post">
    {{ csrf_field() }}
        <div class="form-row">              
            <div class="col-md-4 form-group">
                <label for="search_email">First name:</label>
                <input type="text" name="search_first_name" id="search_first_name" class="form-control" @if(isset(Session::get('inputs')['search_first_name'])) value="{{ Session::get('inputs')['search_first_name'] }}" @endif>
            </div> 
            <div class="col-md-4 form-group">
                <label for="search_last_name">Last name:</label>
                <input type="text" name="search_last_name" id="search_last_name" class="form-control" @if(isset(Session::get('inputs')['search_last_name'])) value="{{ Session::get('inputs')['search_last_name'] }}" @endif>
            </div> 
            <div class="col-md-4 form-group">
                <label for="search_round_number">Round Number:</label>
                <input type="text" name="search_round_number" id="search_round_number" class="form-control" placeholder="" @if(isset(Session::get('inputs')['search_round_number'])) value="{{ Session::get('inputs')['search_round_number'] }}" @endif>
            </div>  
            <div class="col-md-4 form-group">
                <label for="search_location">location:</label>
                <input type="text" name="search_location" id="search_location" class="form-control" 
                 @if(isset(Session::get('inputs')['search_location'])) value="{{ Session::get('inputs')['search_location'] }}" @endif>
            </div> 
            <select name="options" class="col-md-4 form-group">
             <option value="">--- Select From ---</option>
              <option  value="birth_date">Birth Date</option>
              <option  value="CV_grade_date">CV Grade Date</option>
              <option  value="source">Source</option>
              <option  value="recommendation">Recommended</option>                
              <option  value="created_at">Applied</option>
            </select>
            <div class="col-md-4 form-group">
                <label for="search_from_date">From:</label>
                <input type="date" name="search_from_date" id="search_from_date" class="form-control" 
                 @if(isset(Session::get('inputs')['search_from_date'])) value="{{ Session::get('inputs')['search_from_date'] }}" @endif>
            </div> 
            <div class="col-md-4 form-group">
                <label for="search_to_date">To:</label>
                <input type="date" name="search_to_date" id="search_to_date" class="form-control" 
                 @if(isset(Session::get('inputs')['search_to_date'])) value="{{ Session::get('inputs')['search_to_date'] }}" @endif>
            </div>  
        </div>
        <div class="form-row">
            <div class="col-md-12 col-lg-12">
                <button type="submit" class="btn btn-custom"><i class="fa fa-search" aria-hidden="true"></i>Search</button>
                <a href="/users" class="btn btn-custom"><i class="fa fa-times-circle" aria-hidden="true"></i>Clear</a>
            </div>
        </div>
    </form>
</div>

Это мой Контроллер, в котором я попытался реализовать добавление новой переменной со значением «рекомендация» или «источник», присвоить это значение новой переменной, а затем удалить переменную $ options, поэтому я пропускаю

        ->when($options, function ($query) use ($options,$search_from_date,$search_to_date  ) {
           return $query->whereBetween($options, array($search_from_date, $search_to_date));

Вот мой код:

public function index(Request $request) {

    if($request->isMethod('post')){
    $search_first_name =    $request->search_first_name;
    $search_last_name =     $request->search_last_name;
    $search_email =         $request->search_email;
    $search_round_number =  $request->search_round_number;
    $search_location =      $request->search_location;

    $options = Input::get('dropdown');

    if($options == 'recommendation' || 'source')   {
            $recOrSource = Input::get('options');
            unset($options);  
    }

    $search_from_date =      $request->search_from_date;
    $search_to_date =      $request->search_to_date;

    $candidate = DB::table('candidates')
                ->when($search_first_name, function ($query) use ($search_first_name) {
                    return $query->where('first_name', 'like', '%' . $search_first_name . '%');
                })
                ->when($search_last_name, function ($query) use ($search_last_name) {
                    return $query->where('last_name', 'like', '%' . $search_last_name . '%');
                })
                ->when($search_email, function ($query) use ($search_email) {
                    return $query->where('email', $search_email);
                })
                ->when($search_round_number, function ($query) use ($search_round_number) {
                    return $query->where('round_number', $search_round_number);
                })
                ->when($search_location, function ($query) use ($search_location) {
                   return $query->where('location', $search_location);
                })                       
                ->when($options, function ($query) use ($options,$search_from_date,$search_to_date  ) {
                   return $query->whereBetween($options, array($search_from_date, $search_to_date));
                })    
                ->when($recOrSource, function ($query) use ($recOrSource,$search_from_date,$search_to_date  ) {
                   return $query->where(!empty($recOrSource))->whereBetween('created_at', array($search_from_date, $search_to_date));
                })                                                                                     
                ->orderBy('first_name', 'asc')
                ->orderBy('last_name', 'asc')
                ->get();                     

                Session::flash('inputs', [
                    'search_first_name' => $search_first_name,
                    'search_last_name' => $search_last_name,
                    'search_email' => $search_email,
                    'search_round_number' => $search_round_number,
                    'search_from_date' => $search_from_date,
                    'search_to_date' => $search_to_date,
                    'search_location' => $search_location

                    ]);
            }else{
                 Session::forget('inputs');


    $candidate = Candidate::orderBy('first_name', 'asc')
                    ->orderBy('last_name', 'asc')
                    ->get();
                }

    return view('/candidates/index', [
        'candidate' => $candidate
    ]);

}

Я получаю сообщение об ошибке «Неопределенная переменная: параметры», однако я не нашел способа решить эту проблему. И я видел похожие вопросы, но у меня ничего не получалось.

1 Ответ

0 голосов
/ 10 ноября 2018

1) В вашем представлении атрибут <select> name имеет значение options , но в вашем controller вы получаете значение dropdown $options = Input::get('dropdown');. Должно быть:

$ options = Input :: get ('options');

2) Если вы хотите проверить, является ли выбранный параметр recommendation или source, ваш оператор if должен быть:

if ($ options == 'рекомендация' || $ options == 'source')

3) Внутри вашего if оператора вы отменяете переменную $ options, но в строках ниже у вас есть when($option,.., тогда вы должны изменить unset($options); на:

$ options = null;

в противном случае он снова выдаст «Неопределенная переменная: опции».

4) Кроме того, в вашем контроллере вы используете ->when($recOrSource,.., но переменная $recOrSource объявлена ​​внутри вашего if statement, поэтому, если вы не выберете «рекомендуемый» или «источник», вы получите «Не определено» переменная: recOrSource ". Чтобы это исправить, вы должны объявить $recOrSource, т. Е. Вне вашего if, заявление .

$recOrSource = null;

if ($options == 'recommendation' || $options == 'source') {

Подводя итог, изменения, которые вы должны сделать в вашем контроллере :

...
$options = Input::get('options');
$recOrSource = null;

if($options == 'recommendation' || $options == 'source')   {
    $recOrSource = Input::get('options');
    $options = null;
}
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...