My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Validating date range with Laravel

Reuben Frimpong's photo
Reuben Frimpong
·Feb 11, 2021·

2 min read

Dates are a common thing we all work with. One way or another you will reach a point in your application where you would have to work with dates. The Carbon package makes working with dates in Laravel very easy. However, that's not the point of this post. I'm assuming you already know Laravel and have setup your application.

Let's say you have a case where you are collecting two dates, $startDate and $endDate, from your users and you need to make sure the minimum is for the $startDate and $endDate to be same or the $startDate lesser than the $endDate or vice versa. How do we go about this?

Laravel's validation rules to our rescue. We can use the

after,after_or_equal, before, before_or_equal

rules to achieve that. They all take a date input as their parameter. In our scenario we will use after_or_equal or before_or_equal or both.

Depending on how you are handling validation in your project you will know how to include these. If I am using a Request class this is how I will go about it

return[
'start_date' => ['date','before_or_equal:end_date'],
 'end_date' => ['date','after_or_equal:start_date'],
]

It's important that I make sure the input I receive is a date before applying the rules so I don't get any unexpected behaviors. As simple as that. I hope you enjoyed this blog post which also happens to my very first. You can read more from the official docs and you can follow me on Twitter