I need to select users with specific age from model User, but have this error:
DateTime::__construct(): Failed to parse time string (birth) at position 0 (b): The timezone could not be found in the database
part of controller:
$users = User::where(Carbon::parse('birth')->diff(Carbon::now())->format('%y'), '>=', 18)->get();
when i use it in view all working fine:
@foreach ($userss as $user)
<?php $age_year = Carbon::parse($user->birth)->diff(Carbon::now())->format('%y'); ?>
@endforeach
Thanks for answers!
In your controller example, you are trying to parse the string 'birth' instead of the database field 'birth'.
Since you are returning a collection, just run through the returned collections with the filter() method before sending it down to your view. You can also use the age property instead of doing a diff
$users = User::get()->filter(function($user, $key) {
return (Carbon::parse($user->birth)->age >= 18);
});
I did not test this, so you may get some typos, but this is how you will want to accomplish this task.
try this:
User::where('birth','>=', Carbon::now()->subYears(18)->toDateTimeString());
not tested yet, but hope it works!
You can use Carbon
's diff
helper to calculate age, and filter
method to filter objects(User
in this case).
$users = User::get()->filter($user, $key) {
return Carbon\Carbon::now()->diff($user->birth)->y >= 18;
});
There are also other helpers functions available with Carbon
, some are:
// diffInYears(), diffInMonths(), diffInWeeks()
// diffInDays(), diffInWeekdays(), diffInWeekendDays()
// diffInHours(), diffInMinutes(), diffInSeconds()
Please review this for more information: http://carbon.nesbot.com/docs/