"Integrity constraint violation: 1048 Column 'morning' cannot be null" when updating optional values

Published 1 month ago by Gabotronix

Hi, In the admin panel I'm trying to make the damin can update the values for morning and night schedules, however he doesn't have to update both.

Sadly, when leave one of the inputs blank it gives me error with the following message : Integrity constraint violation: 1048 Column 'morning' cannot be null, pretty self explanaroey.

This is my blade template form:

<div class="modal_overlay_maincontainer closeable form_update_modal" data-link="schedules">
    <form id="edit_general_form" class="modal_container" >
        <i class="close fa fa-times-circle" title="Cerrar" ></i>
        <h2 class="modal_title">Editar horario de {{ config('globals.web_name') }}</h2>
        <div class="horizontal_gradient_line" style="align-self:center; margin:10px 0px;"></div>
        <div class="modal_body_check_container">
            <span class="modal_body_options_title old_name">Antiguo valor mañama:</span>
            <span class="modal_body_options_title form_old_value_morning"></span>
        </div>
        <div class="modal_body_check_container">
            <span class="modal_body_options_title old_name">Antiguo valor tarde:</span>
            <span class="modal_body_options_title form_old_value_night"></span>
        </div>
        <input id="schedules_morning" class="modal_input" type="text" placeholder="Horas de apertura por la mañana">
        <input id="schedules_night" class="modal_input" type="text" placeholder="Horas de apertura por la tarde">
        <div class="form_valid_container"></div>
        <div class="form_error_container"></div>
        <div class="horizontal_gradient_line" style="align-self:center; margin:10px 0px;"></div>
        <div class="modal_footer_container">
            <button class="modal_footer_add_button form_update_button" type="button" data-link="schedules" data-id="" data-day="" data-morning="" data-night="" title="Guardar cambios">Guardar</button>
            <button class="modal_footer_reset_button form_reset_button" type="button" title="Resetear los campos">Reset</button>
        </div>
    </form>
</div>

My AJAX call to resource controller (I'm sending scrf token so don't worry about that):


var id = $(this).attr("data-id");
var morning = $('#schedules_morning').val();
var night = $('#schedules_night').val();
console.log(id, morning, night);

$.ajax({
            

                
                async: true,
                cache: false,
                url: 'schedules/' + id,
                type: 'PUT',
                data: 
                {
                    'id' : id,
                    'morning': morning,
                    'night': night
            
                },
                dataType: 'JSON',
                //processData: false,
                //contentType: false,
            
                success: function (data) { 
                    $('.form_valid_container').fadeIn().html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                    form.trigger("reset");
                    console.log(data.success);
                },
            
                error: function (data){
                    var errors = data.responseJSON;
                    console.log(errors);
                
                    $.each(errors , function(){
                        $('.form_error_container').fadeIn().html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                    }); 
                }
                
                
            });

Controller updating method (here I use has() on request variable so I don't know why I'm getting the integruty constraint error really?):

public function update(Request $request , $id)
    {
        $schedule = Schedule::findOrFail($id);
        
        if($request->has('morning')){
            $schedule->morning = $request->morning;
        }
        
        if($request->has('night')){
            $schedule->night = $request->night;
        }

        $schedule->save();
        
        return response()->json([
        
            'schedule' => $schedule,
            'success' => 'Horario actualizado correctamente',
        ]);
    }
Best Answer (As Selected By Gabotronix)
36864
      data: 
               {
                   'id' : id,
                   'morning': morning,
                   'night': night
           
               },

This basically means your request will always contain the morning and night keys, so $request->has('morning') and $request->has('night') will always be true. By default, if the user doesn't fill in the value, the value will be null, which is why you're seeing the current behavior.

In addition to checking if the request contains these keys, also check their value:

if($request->has('morning') && ! is_null($request->input('morning') {
    $schedule->morning = $request->morning;
}
lostdreamer_nl

The error is coming from your DB. Apparently you have the morning field setup as NOT NULL

So either you change your migration to allow for NULL values, or you make sure it's always an empty string instead of NULL before saving.

        $schedule->morning = '';
        if($request->has('morning')){
            $schedule->morning = $request->morning;
        }
Gabotronix

$schedule->morning = ''; didn't work so I guess I'll add ->nullable() to migration

But sure there has to be a better way to handle this

36864
36864
1 month ago (60,610 XP)
      data: 
               {
                   'id' : id,
                   'morning': morning,
                   'night': night
           
               },

This basically means your request will always contain the morning and night keys, so $request->has('morning') and $request->has('night') will always be true. By default, if the user doesn't fill in the value, the value will be null, which is why you're seeing the current behavior.

In addition to checking if the request contains these keys, also check their value:

if($request->has('morning') && ! is_null($request->input('morning') {
    $schedule->morning = $request->morning;
}
Gabotronix

ohh I get it, is the ->input needed or I can just do $request->morning??

36864
36864
1 month ago (60,610 XP)

$request->morning should work. I prefer to be explicit with my request objects.

Please sign in or create an account to participate in this conversation.