Reputation: 318
I want to add a new function called Age
to calculate age of a person using his birthday. So I worked with Resource Controller (RESTFUL). I don't know how to add this function and how to use it in views.
My function is :
public function getBirthday($date){
return (int) ((time() - strtotime($date)) / 3600 / 24 / 365);
}
Upvotes: 1
Views: 90
Reputation: 40909
First of all, add that method that would return person's age to your Person model class:
public function getAgeAttribute() {
return (int) ((time() - strtotime($this->born_at) / 3600 / 24 / 365);
}
In your controller you'll need to pass a model object to the view:
public someControllerAction() {
// get person from the database or create a new model
$person = ...;
return view('some.view')->with(['person' => $person]);
}
And then, in the Blade template you can display age by doing:
{{ $person->age }}
I'm just not sure why you mention resource controllers. Usually they do not have a related view that they use to render HTML, but instead they return plain data, that is later serialized (e.g. to JSON) and used as controller response.
Upvotes: 2