Search code examples
phplaravelpostmanlaravel-query-builder

Laravel : Integrity constraint violation: Column cannot be null


i'm trying to update event name through postman with the following json object:

PUT {{base_url}}events/1 
{
    "name":"this Event Name is Edited"
}

in my controller i'm using sometimes constraint because not all fields must be updated, it could be only 1 field like name, and after that i update the event with update method

EventController.php

    public function update(Request $request, Event $event)
    {
        $request->validate([
            'name' => 'sometimes|string|max:255',
            'description'=>'nullable|string',
            'start_time' => 'sometimes|date',
            'end_time'=> 'sometimes|date|after:start_time',
       ]);

        return $event->update([
            'name' => $request->name,
            'description' => $request->description,
            'start_time' => $request->start_time,
            'end_time' => $request->end_time
        ]);
    }

when i request it gives me error:

Integrity constraint violation: Column start_time cannot be null

so the sometimes constraint doesn't seem to work here, what could be the problem


Solution

  • Just send the data after validation:

    public function update(Request $request, Event $event)
    {
        $payload = $request->validate([
            'name' => 'string|max:255',
            'description'=>'nullable|string',
            'start_time' => 'date',
            'end_time'=> 'date|after:start_time',
        ]);
    
        return $event->update($payload);
    }