match age range to birthdate in database for search filter
im creating search filter
problem is that the age range slider gets example (18,20) but what i have in my database table of user is birthdate column example (1998-05-11)
that's why im getting error because 18,20 age range can't be matched with 1998-05-11 birthdate format
This includes people who are already 18 and not yet 20
// explode the range and set as follows
$minAge = 18;
$maxAge = 20;
// prepare dates for comparison
$minDate = Carbon::today()->subYears($max); // make sure to use Carbon\Carbon in the class
$maxDate = Carbon::today()->subYears($min)->endOfDay();
// then add to the query
whereBetween('birthday', [$minDate, $maxDate])
If you want inclusive range, then adjust tha $minDate as below - then you will get people who are 18 through 20+, but not yet 21:
Use MySQL's Date() functions. They have a ton, like Day(), Week(), Month(), and Year(). You just need to use the correct column types (super simple). Just pop on over to their docs:
@JarekTkaczyk thanks! it works, but i have a little problem, the user has 1970-01-01 and i set the range to 18,45
the user must be in the list but he's not there, i have to adjust the age range to 18-46 and the user with 1970-01-01 showed up. is there any fix for that little problem?
@dinis But it's out of range - the guy is 45 yrs and 2 months old - how would you like to include him in the result? Do you want to take into consideration only YEAR part?
@dinis Check the edited answer above - I don't think it's right to make the range inclusive, but I suppose this is what you want.
@JarekTkaczyk yup you're right i don't want to make it range inclusive. but the user is already in range if the user's birthdate is 1970-01-01 the user just turned 45 this year january 1, that's why the user must be in the list within the range 18-45.
the problem if i add $max+1 that will be year basis even the birthdate month and date is not yet reached by the server date
@dinis Well, it's not logical, 1970-01-01 is not in the range. 1970-02-22 would be first day in range.
Describe exactly the requested behaviour with a few examples. For instance, what about 1969-12-31 ? Or would you like to check only year not the fulll date?
@JarekTkaczyk i have two more question, how can i except from search result list the user who did the search filter?
example i logged in and then i did search filter, my name is included in the list how to not show my name in the list?