Laravel : Integrity constraint violation: Column cannot be null

57 Views Asked by At

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

2

There are 2 best solutions below

0
Denis Sinyukov On BEST ANSWER

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);
}
0
kaamrul On

In some situations, you may wish to run validation checks against a field only if that field is present in the data being validated. To quickly accomplish this, add the sometimes rule to your rule list.

Please check your database or migration file, check start_date fields is nullable or not? if nullable then you can validate this way 'start_time' => 'sometimes|date' if start_date fields is required then you should must validate this way 'start_time' => 'required|date'.

If start_date fields is required update your code this way

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

    return $event->update($data);
}