skip to Main Content

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

Answers


  1. 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);
    }
    
    Login or Signup to reply.
  2. 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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search