unique date validation how to unique date validation on laravel
here is my code
public function store(Request $request)
{
$this->validate($request , [
'date' => "required|unique:holidays".$request->date
]);
try {
$holiday = new Holiday();
$holiday->date = $request->get('date') ?? null;
$holiday->save();
return response()->json(['message' => 'Holiday successfully added.'], 200);
} catch (Exception $e) {
return redirect()->route('holiday.index')->with('error', $e->getMessage());
}
}
i try but date cannot unique validate can you please suggest how to do it
Your syntax is incorrect:
'date' => "required|unique:holidays'
The format is unique:table_name,column_name - you don't explicitly give it the value
@tykus yes sir i change this but not getting any error
'date' => "required|unique:holidays,date"
can i missing someting to add
@tykus i also try this way but not generate validation message
'date' => ["required", Rule::unique("holidays")->where(function ($query) use ($request){
return $query->where('id',$request->id)
->where('date', Carbon::parse($request->date)->format("Y-m-d"));
})->whereNull('deleted_at')]
@van1310 why is the id relevant here?
Can you check how the unique query is looking? If you have debugbar; use that, otherwise dump the query:
public function store(Request $request)
{
\DB::listen(fn ($query) => dump([$query->sql, $query-bindings]));
$this->validate($request , [
'date' => "required|unique:holidays"
]);
// etc...
@tykus
here is output of query
array:2 [
0 => "select count(*) as aggregate from `holidays` where `date` = ? and `id` <> ?"
1 => array:2 [
0 => "23-12-2021"
1 => "23-12-2021"
]
]
@van1310 you have a date string for an id binding??? What does your rule currently look like to produce that ?
@tykus no sir
here is my rule
$this->validate($request , [
'date' => "required|unique:holidays,date,".Carbon::parse($request->date)->format('Y-m-d');
]);
@tykus i found solution
here is my code for validation
$request['date'] = Carbon::parse($request->date)->format("Y-m-d");
$this->validate($request , [
'date' => ["required", Rule::unique("holidays")->where(function ($query) use ($request){
return $query->whereDate('date', $request->date);
})->whereNull('deleted_at')]
]);
I ran into this issue on Laravel 11 too.
I think because each database driver handle date migration datatype differently.
In my case SQLite (I think it) has smallest date datatype as YYYY-MM-DD HH:MM:SS so, the input YYYY-MM-DD will be always unique when compares to value in the table.
My solution is:
'date' => ['required', 'date', function ($attribute, $value, $fail) {
if (Holiday::query()->where('date', Carbon::create($value))->exists()) {
$fail('the date is already taken.');
}
}],
Please sign in or create an account to participate in this conversation.