I want to write a function that refers to that birthdate entry..
Asked
Active
Viewed 329 times
-1
-
have you tried anything so far? – Russ J Feb 14 '19 at 03:35
-
yeah definitely – TheBAST Feb 14 '19 at 03:54
-
Please post the code that you have tried. We can help you much better that way. – Russ J Feb 14 '19 at 03:55
-
yeah changed it – TheBAST Feb 14 '19 at 04:02
2 Answers
0
We can use below code.
$birthDate = '31-07-1983';
$data = [
'age'=> call_user_func(function() use( $birthDate){
return (date('Y') - date('Y', strtotime($birthDate)));
})
];
print_r($data);

Abhijeet Jadhav
- 188
- 1
- 4
0
Considering age
is a calculated field and will change every day, this should not be data stored in your database, and therefore shouldn't need to be in your factory.
I'd remove the field from the database and the factory, and add an accessor to your model:
// Make sure birthdate is cast to a Carbon date.
protected $dates = [
'birthdate',
];
// Define the "age" property accessor.
public function getAgeAttribute()
{
return now()->diffInYears($this->birthdate);
}
With the accessor, you can access the field as a property:
$ci = App\CriminalInfo::find(1);
dd($ci->age);
You can also add it to the $appends
property if you want to see it in the model's array/json output.

patricus
- 59,488
- 15
- 143
- 145