Laravel 5 How to change Date Format from Boostrap datepicker in Controller before Validation

i want to change the date format in controller before doing validation. Below is my view

<input type='text' class="form-control" id='datePicker' value="{{old('dateRegister')}}" name="dateRegister"/>

<script type="text/javascript">
    format: 'DD - dd MM yyyy',       

The format i want to show to the customer when they select the datepicker is DD - dd MM yyyy

Now in Controller Store Function:

public function store(Request $request)
    $rules = array(
        'dateRegister' => 'date_format:Y-m-d|required|unique:events,dateRegister,NULL,id,users_id,'.\Auth::id(),
    $messages = array(
        'dateRegister.unique' => 'You have already register this event in this date'

    $validator = Validator::make(Input::all(), $rules, $messages);
        return back()->withInput()->withErrors($validator);
    elseif ($validator->passes()){
        $input = $request->all();
        // MODIFIED DATE
        $date = str_replace("-", "", $request->dateRegister);
        $input['dateRegister'] = Carbon::parse($date)->format('Y-m-d');
    return back();

Here in $rule i need to check that each user can only have unique date register. Since the format for storing the date in database is Y-m-d, I am able to modified the date format and store in database.

But i don't how to modified the date format before validation. What should i do in this part? i keep getting this validation error: The dateRegister does not match the format Y-m-d.

vitorfavila replied 8 months ago

If you're workin with a Model: Take a look at Mutators

With mutators you can create a method in your Model:

public function setDateAttribute($value)
    $this->attributes['date'] = 'convertion rules';

If not, see Carbon createFromFormat method.

Elsner Technologies replied 8 months ago

First parse your date field as Carbon object.

$createdAt = Carbon::parse(your_date);

Then you can use

$date = $createdAt->format('M d Y');

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us