Viewed   92 times

I use following date validation for incoming POST request.

'trep_txn_date' => 'date_format:"Y-m-d H:i:s.u"'

This will only allow a date of this kind i.e. 2012-01-21 15:59:44.8

I also want to allow date without the TIME e.g. 2012-01-21, which when sent to mysql db will automatically store as 2012-01-21 00:00:00.0

Is there a way I can do this using a Laravel's existing validation rules. Is there a way to define multiple formats in date_format rule something like below.

'trep_txn_date' => 'date_format:"Y-m-d H:i:s.u","Y-m-d"' //btw this didn't work.

Thanks,

K

 Answers

1

The date_format validator takes only one date format as parameter. In order to be able to use multiple formats, you'll need to build a custom validation rule. Luckily, it's pretty simple.

You can define the multi-format date validation in your AppServiceProvider with the following code:

class AppServiceProvider extends ServiceProvider  
{
  public function boot()
  {
    Validator::extend('date_multi_format', function($attribute, $value, $formats) {
      // iterate through all formats
      foreach($formats as $format) {

        // parse date with current format
        $parsed = date_parse_from_format($format, $value);

        // if value matches given format return true=validation succeeded 
        if ($parsed['error_count'] === 0 && $parsed['warning_count'] === 0) {
          return true;
        }
      }

      // value did not match any of the provided formats, so return false=validation failed
      return false;
    });
  }
}

You can later use this new validation rule like that:

'trep_txn_date' => 'date_multi_format:"Y-m-d H:i:s.u","Y-m-d"' 

You can read more about how to create custom validation rules here: http://laravel.com/docs/5.1/validation#custom-validation-rules

Monday, December 12, 2022
2

You can use one of two ways of creating a Carbon instance from that date string:

1. Create a new instance and pass the string to the constructor:

// From a datetime string
$datetime = new Carbon('2016-01-23 11:53:20');

// From a date string
$date = new Carbon('2016-01-23');

// From a time string
$time = new Carbon('11:53:20');

2. Use the createFromFormat method:

// From a datetime string
$datetime = Carbon::createFromFormat('Y-m-d H:i:s', '2016-01-23 11:53:20');

// From a date string
$date = Carbon::createFromFormat('Y-m-d', '2016-01-23');

// From a time string
$time = Carbon::createFromFormat('H:i:s', '11:53:20');

The Carbon class is just extending the PHP DateTime class, which means that you can use all the same methods including the same constructor parameters or the createFromFormat method.

Sunday, November 13, 2022
 
mattdmo
 
2

I guess as per laravel upgrade guide we should return HttpResponseException

protected function failedValidation(Validator $validator)
{
    $errors = $validator->errors();
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }

    throw new HttpResponseException(response()->json($response));
}
Wednesday, September 14, 2022
2

Instead of change the format of the created_at column, I suggest that you should update the start and end to beginning of the first date and the ending of the last date. The Carbon objects should be passed to the whereBetween method instead of their string representation.

$arr = [
   'start' => Carbon::parse(substr(request()->get('d'), 4, 11))->startOfDay(),
   'end' =>  Carbon::parse(substr(request()->get('d'), 64, -44))->endOfDay()
];

// Both `start` and `end` are Carbon objects
$builder = $query->whereBetween('created_at', [$arr['start'],$arr['end']]);
Tuesday, September 6, 2022
 
3

Try to remove web middleware if you're using 5.2.27 or higher. The thing is now Laravel automatically applies web middleware to all routes inside routes.php and if you're trying to add it manually you can get errors.

app/Providers/RouteServiceProvider.php of the 5.2.27 version now adds web middleware to all routes inside routes.php:

protected function mapWebRoutes(Router $router)
{
    $router->group([
        'namespace' => $this->namespace, 'middleware' => 'web',
    ], function ($router) {
        require app_path('Http/routes.php');
    });
}
Sunday, August 21, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :