Grof
Grof

Reputation: 121

Format date in validation message with Laravel 5

In my database i have date field in format Y-m-d H:i:s. What I want is, that this date is always bigger then this moment, when adding new item in database. I check this with laravel's validator:

Validator::make->($request->all(), [ 'date'=>'date|after:'.date(Y-m-d H:i:s) ]);

The problem is, that my page is in different languages, and each language has different date formats. Sometimes I want default format, sometimes i want d.m.Y H:i:s, and so on.. I made translations for different languages in resources/lang directory. For validation, I translated existing validation.php file, but the problem is, I don't know how to format date, if that is even possible with this approach. For now, my date is always in default format, the one I compare my input with. My validation.php file looks like this:

<?php

return [
   'after' => 'The :attribute must be a date after :date.'
];

My question now is, how to format :date attribute. Any help would be appreciated.

I tried already:

'after' => 'The :attribute must be date after'.date(format, strtotime(':date'))

But it doesn't do anything.

Upvotes: 1

Views: 2556

Answers (2)

mike peyer
mike peyer

Reputation: 11

I'm not sure if it solves your problem, but I tested this:

$dateFormat = 'j.n.Y';
$this->validate($request, [
  'date' => 'date_format:'.$dateFormat.'|after:' . now()->format($dateFormat)
]);

and it seems to work. Changing the $dateFormat, it displays errors correctly.

Upvotes: 1

Dinoop
Dinoop

Reputation: 497

The dates will be always passed into the PHP strtotime function.

To make date always bigger than this moment you can simply use the term now. Laravel make it pretty simple as below.

Validator::make->($request->all(), [
 'date'=>'date|after:now'
]);

Upvotes: 0

Related Questions