Laravel Searching For Date - Check If String Is An Actual Date, Or A Month

- 1 answer

In my app I have a search function which I use for searching my appointments. It's a simple approach using LIKE to find and match any string being searched for.

The tricky part is, that I also want to be able to search for "january" and return all results found that were created_at is january. Next to this, I want to be able to search for "24 jan" or "24 january" and return all appointments that were created on the 24th of january. I can do this using either one of the following:

When searching for "january":

$result = Carbon::createFromFormat('F', $search)

When searching for "24 jan" for example:

$result = Carbon::createFromFormat('d M', $search)

It all works IF I indeed do a search for "january". But when I search for something else, like "doctor", it fails and gives me an error. My question is, how can I check if the search string is a date (or simply a month or a day and a month as posted above) and return true if it's a match, but false if it's not?



The procedural version of PHP's DateTime object constructor does return false if the string provided is not a valid date:

date_create("Some string that isn't a date"); // returns false

I don't know too much about Laravel, but if the Carbon class you are using extends PHP's own DateTime class then you may find their own implementation of such things.