I have a MySQL table called purchases
and a model called Purchase
in Laravel that is related to it. My table has two columns, quantity
and unit_cost
. The total cost of a purchase is not a column in my table. Instead, it is defined by an accessor in Laravel that multiplies unit_cost
by quantity
and returns it as total_cost
.
Now I am trying to define a trend metric in Laravel nova that is supposed to output the value of my daily sales in the selected range. When I try to use return $this->sumByDays($request, Purchase::class, 'total_cost')
it gives me an error that says total_cost
is not a column.
Fair enough! So, I tried to use Purchase::selectRaw(DB::RAW('unit_cost * quantity AS total_cost'))
in the second argument, but it didn’t work. I saw multiple posts, none of them could solve the problem of accessing a model accessor in Laravel Nova metrics. Any help is appreciated.
Advertisement
Answer
Unfortunately you can’t use the built-in sumByDays
helper function.
But good news! You can still implement it yourself within the calculate
function. Just make sure your function returns a LaravelNovaMetricsTrendResult
.
Something like this:
$purchases = DB::table('purchases') ->select(DB::raw('quantity * unit_cost as total_cost')) ->groupBy(DB::raw('DATE(created_at) DESC')) ->get(); return new TrendResult() ->trend($purchases);
I don’t have time to test this at the moment but it should get you started.