Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

codermans's avatar

Laravel 5 How to do the validation for checking the unique Record Date for each User during Update

Hi i need to know how to do the validation checking on unique Record Date when a user update his report.

Here when he update the record without changing the record date, there should be no error when update. But when he change the record date, here we should do the checking whether the date he changed is duplicated with the other date that he had stored in the database.

The store function work well, but the update function is not working properly in validation.

Below are my store function:

    public function store(Request $request)
    {      
    $input = $request->all();
    $date = str_replace("/", "", $input['recordDate']);
    $input['recordDate'] = Carbon::parse($date)->format('Y-m-d');
    $request->replace($input);

    $rules = array(
        'recordDate' => 'date_format:Y-m-d|required|unique:records,recordDate,NULL,id,users_id,'.\Auth::id(),
    );
    $messages = array(
        'recordDate.required'=>'Record Date is Required',
        'recordDate.unique' => 'This Record Date is already exists'
    );

    $validator = Validator::make($request->all(), $rules, $messages);
    if($validator->fails()){
        return back()->withInput()->withErrors($validator);
    } 
    elseif ($validator->passes()){
        Auth()->user()->records()->create($input);
    }
    return back();
}

Below is my update function:

    public function update(Request $request, Record $record)
    {
    $input = Input::except('_method', '_token');
    $date = str_replace("/", "", $input['recordDate']);
    $input['recordDate'] = Carbon::parse($date)->format('Y-m-d');
    $request->replace($input);

    $rules = array(
        // HOW TO MIDIFIED THE UNIQUE UPDATE HERE??
        'recordDate' => 'date_format:Y-m-d|required|unique:records,recordDate,'.$record->users_id,
    );
    $messages = array(
        'recordDate.unique' => 'This Record Date is already added'
    );

    $validator = Validator::make($request->all(), $rules, $messages);
    if($validator->fails()){
        return back()->withInput()->withErrors($validator);
    } 
    elseif ($validator->passes()){
        $record->update($input);
    }

    return back();
}
0 likes
0 replies

Please or to participate in this conversation.