Laravel - Некоторые поля сохраняют ноль в базе данных в моем Laravel проекте - PullRequest
0 голосов
/ 11 апреля 2020

Я получил некоторые данные из jQuery в Laravel -5.8:

Класс модели:

class HrLeaveRequest extends Model
{
   protected $table = 'hr_leave_requests';

   protected $primaryKey = 'id';
   protected $fillable = [
              'id',
              'company_id',
              'employee_id',
              'reason',
              'leave_type_id',
              'commencement_date',
              'resumption_date',
              'authorized_days',
              'available_days',
              'leave_status',
              'no_of_days',
              'relief_officer_id',
              'contact_person_fullname',
              'contact_person_phone',
              'contact_person_address',
              'created_by',
              'created_at',
              'updated_by',
              'updated_at',
              'is_active'
          ];
   protected $dates = [];
   protected $casts = [];

   public function reliefofficer()
   {
      return $this->belongsTo('App\Models\Hr\HrEmployee','relief_officer_id');
   }    

   public function leavetype()
   {
      return $this->belongsTo('App\Models\Hr\HrLeaveType','leave_type_id');
   }
}

Контроллер

public function store(StoreLeaveRequestRequest $request)
{
        $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,
            '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,
        ]);   
        Session::flash('success', 'Leave Request is created successfully');
        return redirect()->route('service.leave_requests.index');              
}



    <script type="text/javascript">
    $(document).ready(function() {
        $(document).on('change', '#leave_type', function() {
            var air_id =  $(this).val();

            var a = $(this).parent();

            var op = "";

            $.ajax({
                type: 'get',
                url: '{{ route('get.leavecounts.all') }}',
                data: { 'id': air_id },
                dataType: 'json',      //return data will be json

                success: function(data) {
                    $('#authorized_leave_days').val(data.authorizedleavedays);
                    $('#available_leave_daysx').val(data.availableleavedays);

                     let sumAvailableDays = parseInt(data.authorizedleavedays) - parseInt(data.availableleavedays);

                    $("#available_leave_days").val(sumAvailableDays);
                },
                error:function(){

                }
            });
        });
    });
    </script>

Я получил 'authorized_days 'and' available_days 'из jQuery выше и загрузили результат в:

view

   <form  action="{{route('service.leave_requests.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
       {{csrf_field()}}
          <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> 
            <input type="hidden" id="available_leave_daysx" class="form-control" value="0" >
          <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>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%;" disabled>
            </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%;" disabled>
            </div>
          </div>

    <div class="card-footer">
            <button type="submit" id="submit_create" class="btn btn-primary">{{ trans('global.save') }}</button>

' service.leave_requests.index ')}}' "class =" btn btn -default "> Отмена

<script type="text/javascript">
$(document).ready(function() {
    $(document).on('change', '#leave_type', function() {
        var air_id =  $(this).val();

        var a = $(this).parent();

        var op = "";

        $.ajax({
            type: 'get',
            url: '{{ route('get.leavecounts.all') }}',
            data: { 'id': air_id },
            dataType: 'json',      //return data will be json

            success: function(data) {
                $('#authorized_leave_days').val(data.authorizedleavedays);
                $('#available_leave_daysx').val(data.availableleavedays);

                 let sumAvailableDays = parseInt(data.authorizedleavedays) - parseInt(data.availableleavedays);

                $("#available_leave_days").val(sumAvailableDays);
            },
            error:function(){

            }
        });
    });
});
</script>

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

Затем я сделал:

дд ($ Leaverequest);

, и у меня есть это:

дд ($ Leaverequest):

  #attributes: array:17 [▼
    "leave_type_id" => "1"
    "employee_id" => 2
    "commencement_date" => Carbon\Carbon @1586559600 {#804 ▶}
    "resumption_date" => Carbon\Carbon @1587769200 {#790 ▶}
    "authorized_days" => null
    "available_days" => null
    "no_of_days" => 11
    "relief_officer_id" => "10"
    "contact_person_fullname" => "assasasaddddd"
    "contact_person_phone" => "08099448844"
    "contact_person_address" => "xxzxzxzxz ddds"
    "company_id" => 1
    "created_by" => 2
    "created_at" => "2020-04-10 22:10:41"
    "is_active" => 1
    "id" => 9
  ]

Вы видите:

    "authorized_days" => null
    "available_days" => null

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

Спасибо

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