Laravel проверка не удалась в запросе на отпуск - PullRequest
0 голосов
/ 14 апреля 2020

У меня есть этот Laravel -5.8 код для проверки в запросе на отпуск:

Правила запроса:

class StoreLeaveRequestRequest extends FormRequest
{
public function rules()
{
    return [
        'leave_type_id' => [
            'required'              
        ],   
        'commencement_date' => [
            'required', 
            'date',
            'date_format:Y-m-d',
        ],          
        'resumption_date' => [
            'required', 
            'date',
            'date_format:Y-m-d',
            'after:commencement_date'
        ],
        'relief_officer_id' => [
            'required'              
        ],               
        'contact_person_fullname' => [
            'required',
            'string',
            'min:5',
            'max:100'
        ], 
        'contact_person_phone' => [
            'required',
            'phone:NG,mobile', // official
            'max:14'
        ],  
        'contact_person_address' => [
            'required',
            'string',
            'min:5',
            'max:500'
        ],            

    ];
  }
}

Контроллер

public function store(StoreLeaveRequestRequest $request)
{
    if (! Gate::allows('leave_request_create')) {
        return abort(401);
    }
    DB::beginTransaction(); 
    try {
        $userEmployee = Auth::user()->employee_id;
        $commencementDate   = Carbon::parse($request->commencement_date);
        $resumptionDate     = Carbon::parse($request->resumption_date);
        $holidays = DB::table('hr_holiday_dates')->select('holiday_date')->whereYear('created_at', '=', date('Y'))->get()->pluck('holiday_date')->toArray();
        $days = $commencementDate->diffInDaysFiltered(function (Carbon $date) use ($holidays) {
            return $date->isWeekday() && !in_array($date, $holidays);
        }, $resumptionDate) + 1;         

        if ($days > $request->available_days)
        {
            Session::flash('info', 'Leave days cannot be greater than available days!');
            return redirect()->back()->withInput();               
        }
        $leaverequest = HrLeaveRequest::create([
            'leave_type_id'             => $request->leave_type_id,
            'employee_id'               => $userEmployee,
            'commencement_date'         => $commencementDate,
            'resumption_date'           => $resumptionDate,  
            'authorized_days'           => $request->authorized_days,
            'available_days'            => $request->available_days,
            'no_of_days'                => $days,//$request->no_of_days,
            'reason'                    => $request->reason,
            'relief_officer_id'         => $request->relief_officer_id,
            'contact_person_fullname'   => $request->contact_person_fullname,
            'contact_person_phone'      => $request->contact_person_phone,
            'contact_person_address'    => $request->contact_person_address,
            'company_id'        => Auth::user()->company_id,
            'created_by'        => Auth::user()->id,
            'created_at'        => date("Y-m-d H:i:s"),
            'is_active'         => 1,
        ]);

    DB::commit();     
        Session::flash('success', 'Leave Request is created successfully');
        return redirect()->route('service.leave_requests.index');        
    } 
    catch (Exception $exception) 
    {
    DB::rollback();
        Session::flash('error', 'Action failed!');
        return redirect()->route('service.leave_requests.index');  
    }        
}

create.blade

 <section class="content">
             
    @if(Session::has('info'))
      <p>{{ Session::get('info') }}</p>
    @endif      
    <br>
    @include('partials._messages')                    
    <div class="container-fluid">                                    
        <div class="row">
            <div class="col-md-12">
            <!-- general form elements -->
             <div class="card card-secondary">
                <div class="card-header">
                    <h3 class="card-title">Create Leave Request</h3>
                </div>
                <!-- /.card-header -->
                <!-- form start -->
       <form  action="{{route('service.leave_requests.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
           {{csrf_field()}}
           <div class="card-body">
            <div class="form-body">
            <div class="row">

              <div class="col-sm-4">
                <div class="form-group">
                    <label>Leave Type:<span style="color:red;">*</span></label>
                    <select id="leave_type" class="form-control select2bs4" data-placeholder="Choose Leave Type" tabindex="1" name="leave_type_id" style="width: 100%;">
                        <option value="">Select Leave Type</option>
                        @if($leavetypes->count() > 0)
                            @foreach($leavetypes as $leavetype)
                                <option value="{{$leavetype->id}}">{{$leavetype->leave_type_name}}</option>
                            @endforeach
                        @endif
                    </select>
                </div>
              </div> 
              <div class="col-sm-4">
                <div class="form-group">
                    <label>Authorized Leave Days:</label>
                    <input type="number" id="authorized_leave_days" class="form-control authorized_days" name="authorized_days" value="{{old('authorized_days')}}" style="width: 100%;" readonly>
                </div>                                                                                       
              </div> 
              
              <div class="col-sm-4">
                <div class="form-group">
                    <label>Available Leave Days:</label>
                    <input type="number" id="available_leave_days" class="form-control available_days" name="available_days" value="{{old('available_days')}}" style="width: 100%;" readonly>
                </div>
              </div>  
                
              <div class="col-sm-4">
                <div class="form-group">
                    <label>Commencement Date:<span style="color:red;">*</span></label>
                    <input type="date" class="form-control" placeholder="dd/mm/yyyy" name="commencement_date" value="{{old('commencement_date')}}"  min="{{Carbon\Carbon::now()->addDay()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}">
                </div>
              </div>                    
              <div class="col-sm-4">
                <div class="form-group">
                    <label>Resumption Date:<span style="color:red;">*</span></label>
                    <input type="date" class="form-control" placeholder="dd/mm/yyyy" name="resumption_date" value="{{old('resumption_date')}}"  min="{{Carbon\Carbon::now()->addDay()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}">
                </div>
              </div> 
              <div class="col-sm-4">
                <div class="form-group">
                    <label>Relief Officer:<span style="color:red;">*</span></label>
                    <select class="form-control select2bs4" data-placeholder="Choose Relief Officer" tabindex="1" name="relief_officer_id" style="width: 100%;">
                        <option value="">Select Relief Officer</option>
                        @if($reliefofficers->count() > 0)
                            @foreach($reliefofficers as $reliefofficer)
                                <option value="{{$reliefofficer->id}}">{{$reliefofficer->employee_code}} - {{$reliefofficer->first_name}} {{$reliefofficer->last_name}}</option>
                            @endforeach
                        @endif
                    </select>
                </div>
              </div>               
             
              <div class="col-sm-12">
                <div class="form-group">
                    <label>Reason</label>
                    <textarea rows="2" name="reason" class="form-control" placeholder="Enter Reason here" value="{{old('reason')}}"></textarea>
                </div>
              </div>                                              
                
              <div class="col-sm-4">
                <div class="form-group">
                    <label>Contact Person Name:<span style="color:red;">*</span></label>
                    <input type="text" name="contact_person_fullname" placeholder="Enter contact person name here" class="form-control" value="{{old('contact_person_fullname')}}">
                </div>
              </div>
                
              <div class="col-sm-4">
                <div class="form-group">
                    <label>Contact Person Phone:<span style="color:red;">*</span></label>
                    <input  type="number" name="contact_person_phone" placeholder="e.g. 23455996633" class="form-control" value="{{old('contact_person_phone')}}" pattern="[0-9]{13}" style="width: 100%;" maxlength="14">
                </div>
              </div>
          
                                
              <div class="col-sm-4">
                <div class="form-group">
                    <label>Contact Person Address:<span style="color:red;">*</span></label>
                    <textarea rows="2" name="contact_person_address" class="form-control" placeholder="Enter Contact Person Address here" value="{{old('contact_person_address')}}"></textarea>
                </div>
              </div>

           </div>
         </div>
        </div>          
        <!-- /.card-body -->
        <div class="card-footer">
                <button type="submit" id="submit_create" class="btn btn-primary">Save as Draft</button>
        </div>           
           
        </form>
        </div>
        <!-- /.card -->
       </div>
       <!--/.col (left) -->
      </div>
    <!-- /.row -->
    </div><!-- /.container-fluid -->
</section>

Из приведенного выше кода в контроллере:

        if ($days > $request->available_days)
        {
            Session::flash('info', 'Leave days cannot be greater than available days!');
            return back()->withInput();                
        }

следует проверить, превышает ли $ days значение $ request-> available_days

тогда должно появиться это сообщение:

Дни отпуска не могут превышать доступные дни! '

и оставаться с полями ввода.

I обнаружил, что хотя данные не сохраняются. но ни одно сообщение, а также поля ввода не очищены?

Как мне решить эту проблему?

Спасибо

1 Ответ

0 голосов
/ 14 апреля 2020

сначала для входных значений, это должно помочь сохранить предыдущие значения.

return redirect()->back()->withInput();

также в вашей форме, вам также нужно иметь old() в атрибуте значения. например

<input type="text" name="available_days" value="{{old('available_days')}}">

секунда для сообщения, которое необходимо отобразить в форме создания,

@if(Session::has('info'))
<p>{{ Session::get('info') }}</p>
@endif
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...