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
Just send the data after validation:
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