1

I want to insert into my 'pointages' table the following data elements: matricule, datep, balance, nbrj premium work and site, but it gives me the following error:

General error: 1364 Field 'matricule' doesn't have a default value

Here is my code:

SalarieController

public function addMultiple(Request $request){
           foreach($request->get('items') as $item){
              $pointage = Pointage::create([
             'matricule' => $item['matricule'], 
              'datep' => $item['date'],
             'solde' => $item['salaire'], 
             'nbrj' => $item['nbrj'], 
             'prime' => $item['prime'], 
             'ouvrage' => $item['ouvrage'], 
             'chantier' => $item['chantier']
             ]);
            }
              return redirect("mois");
          }

jQuery code

  $('.add-all').on('click', function() {
        var items = [];
        let valu = $('#datePicker').val();
       let valu1 = $('#chan option:selected').html();
       let valu2 = $('#ouv option:selected').html();
       ///


      $("tr").each(function(i,r){
        if ( i > 0 && $(r).find("input").first().prop("checked"))
        {  

         // let value = $('#nbr').val();
         let value = parseInt($(r.cells[6]).find('input').val());
          let prime = parseInt($(r.cells[7]).find('input').val());
          let sum = (((parseInt($(r.cells[5]).text()))/24) * value ) + prime;
          $(r).find("input").first().replaceWith('<span style="color: green;font-weight: bolder;">✔</span>');//✓ -

          //items.push({value,prime,sum});
         items.push({"matricule": r.cells[3].innerText,"date" : valu, "salaire": sum, "nbrj" : value , "chantier" : valu1 , "ouvrage" : valu2 , "prime": prime })
              }
             // console.log(items);
                                    });
//ajax 
 $.ajax({ 
         method      : 'POST', 
         url       : 'mois', 
         headers: {
             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
         },
         data      : {"items":items}, // pass in json format 
         success   : function(data) {
             console.log(data);
         },
         error : function(err){
             console.log(err)
         }
     });

//fin ajax 
      });  

mois.blade.php

<div id='form1'>
    @if ($message = Session::get('success'))
    <div class="alert alert-success">
        <p>{{ $message }}</p>
    </div>
    @endif

     {!! csrf_field() !!}

    <div class="form-group">
     <label>Date:</label>
      <input type="date" id="datePicker" name="date" class="form-control" placeholder="date naissance">
    </div>

    <div class="form-group">
      <label>Select Chantier:</label>
      {!! Form::select('chantier_id',[''=>'--- Select Chantier ---']+$chantiers,null,array('class' => 'form-control','id' => 'chan')) !!}
    </div>

    <div class="form-group">
      <label>Select Ouvrage:</label>
      {!! Form::select('ouvrage_id',[''=>'--- Select Ouvrage ---'],null,array('class' => 'form-control','id' => 'ouv')) !!}
    </div>

    <div class="form-group">
      <label>Nbre de jour</label>
        <input type="text" name="nbr" id='nbr' class="form-control" placeholder="nbre de jour" value="1">
      <span id='error'>Input can not blank</span>
    </div>

    <div class="form-group col-md-offset-5 ">
      <button class="btn btn-success " type="submit" id="hide">valider</button>
    </div>

  </div>

 <div id='form2'>
    <h3>form group 2</h3>
    <h4>DATE : <span id="dateE"></span></h4>
    <h4>chantier : <span id="ch"></span></h4>
    <h4>ouvrage : <span id="ou"></span></h4>
      <div class="form-group col-md-offset-5 ">
        <button class="btn btn-success add-all" type="submit" id="hide">Pointage</button>
      </div>
   <table class="table table-bordered" id="mytable">
        <tr>
            <th>Archive</th>
            <th><input type="checkbox" id="check_all"></th>
            <th>S.No.</th>
            <th>matricule</th>
            <th>nom & prenom</th>
            <th>salaire net</th>
            <th>nbre de jour </th>
            <th>prime</th>
        </tr>
        @if($salaries->count())
            @foreach($salaries as $key => $salarie)
                <tr id="tr_{{$salarie->id}}">
                  <td>archive</td>
                  <td><input type="checkbox" class="checkbox" data-id="{{$salarie->id}}"></td>
                  <td>{{ ++$key }}</td>
                  <td>{{ $salarie->matricule }}</td>
                  <td >{{ $salarie->nom }} {{ $salarie->prenom }}</td>
                  <td><input type="hidden" name="salaire" value="{{ $salarie->salairenet }}">{{ $salarie->salairenet }}</td>
                  <td ><input type="text" class='input2' name="nbreJ" class="form-control" ></td>
                  <td><input type="text" name="prime" class="form-control" value="0"></td>
                </tr>
            @endforeach
        @endif
    </table>
 </div>
<!--</form>-->
</div>

migration create_pointages_table.php

 Schema::create('pointages', function (Blueprint $table) {
            $table->increments('id'); 
            $table->string('matricule'); 
            $table->date('datep');
            $table->double('nbrj');
            $table->double('prime')->nullable();
            $table->double('solde');
            $table->string('ouvrage'); 
            $table->string('chantier'); 

            $table->timestamps();
        });
Watercayman
  • 7,970
  • 10
  • 31
  • 49
Najib Marzouk
  • 355
  • 5
  • 19

2 Answers2

2

Couple of things to check for. On your Pointages model, make sure you have matricule set as fillable:

protected $fillable = [
    'matricule', 'otherVars',
];

If it isn't fillable on the model, Laravel will return a null value to the database no matter what you fill in. As the DB field 'matricule' is not nullable in your code, this might be the source of the error.

The other thing to check on is what your middleware is doing for this particular route. In your Kernal.php, Laravel defaults to have a middleware that makes empty strings null. So, if your user doesn't type anything into the matricule field on your form -- if this middleware is in place, it will make it null.

Look for this:

protected $middleware = [
    // OtherMiddleware
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

If it is there, remove it (for testing). If the code now works, you know what the issue was.

Watercayman
  • 7,970
  • 10
  • 31
  • 49
1

You will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.

Fillable you specify which fields are mass-assignable in your model, you can do it by adding the special variable $fillable to the model.

app/pointages.php

class pointages extends Model {
      protected $fillable = ['matricule']; 
      //only the field names inside the array can be mass-assign
}

More details: What does “Mass Assignment” mean in Laravel (Link)

Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64