How do I load a model function before viewing the record?
I am viewing a record but I want to mutate the data with a function that is defined in my model. How do I do this?
8 Replies
I am showing it in a custom view
share the code
This is my function in my Company model:
public function calculateRevenue()
{
return $this->orders()
->where('paid', true)
->selectRaw('sum(price) as sum, YEAR(created_at) as year, MONTH(created_at) as month')
->groupBy('year', 'month')
->get();
}
I want to define $record->revenue = $record->calculateRevenue() somewhere
Before loading the view
mutate function in the ViewCompany.php will only get me an array and not the model.
are you using a custom view field?
What are you rendering in the view?
you can access
{{ $getRecord()->field }}
inside the viewBut it's not a field yet
It s a function in my model
I am doing a $record->revenue->groupBy in my view
You could use an accessor to customize an attribute
https://laravel.com/docs/10.x/eloquent-mutators#defining-an-accessor
Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
Thats probably the way I would go then
Thanks for that mate