Our week-long focus on validation continues with another tip pulled from the brand-new 3rd edition of the Mastering Laravel Validation Rules book.
Just because we have rules that validate a piece of data as a date or integer, that doesn't mean we get a date or integer out when we access the validated data. (That would be cool though!)
Laravel introduced typed data access helpers on the request.
For example: $request->date('meeting_date')
will return a Carbon
date object, and $request->int('age')
will return an integer.
While this works, it bypasses the validated data set. If we're accessing the request directly and someone later changes the validation rules, we could potentially be using unvalidated data.
Recently though, Laravel added the safe()
helper on the request, which only accesses validated data, but also has access to those typed data access helpers.
Now with $request->safe()->date('meeting_date')
, we get the typed data, and we guarantee it will always be validated data.
Here to help,
Joel
P.S. The validation book isn't just about how to use individual rules. It also has a higher level opinionated view of how to use validation consistently for data integrity and security.