SVM
SVM

Reputation: 433

How to validate date in laravel

In validate method I have following :

$this->validate($request, ['test_date' => 'required|unique:test_db']);

The test_date in test_db is stored as unix time. On submission of form, I get $request->get('test_date') in mm/dd/Y

The unique validation does not work because I get date in mm/dd/Y which is different from db (unix time).

How to make it unique in this validation?

Upvotes: 2

Views: 7428

Answers (3)

iamab.in
iamab.in

Reputation: 2070

You can try this:

//get date from request
$date = $request->get('test_date');

//add the converted date to request
$request->request->add(['new_date_field'=> DateTime::createFromFormat('m/d/Y', $date)->getTimestamp()]);

//validate the updated date field
$this->validate($request, ['new_date_field' => 'required|unique:test_db']);

Adding fields to the request : Laravel is there a way to add values to a request array

UPDATE : You can update existing field using offsetSet method:

    //get date from request
    $date = $request->get('test_date');

    //update date in request
    $request->offsetSet('test_date', DateTime::createFromFormat('m/d/Y', $date)->getTimestamp());

    //validate the updated date field
    $this->validate($request, ['test_date' => 'required|unique:test_db']);

Updating request fields : Modify request field value before saving in Laravel 5

Upvotes: 4

Sagar Dave
Sagar Dave

Reputation: 97

Laravel Provide feature called Accessors and mutators.

Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances.

For more information visit: https://laravel.com/docs/5.5/eloquent-mutators#accessors-and-mutators

Hope this will help you.

Upvotes: 0

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26288

I think if you change the date format then everything will be fine, so try this:

$date = $request->get('test_date');

$newDate = date('d-m-Y', strtotime($date ));

use this $newDate in the validation.

Upvotes: 0

Related Questions