How to format output in view?
Morning All
I'm just working on a query that shows the users most popular vehicle from orders, but the output in the view ends up in brackets & curly braces?
Please can someone advise how i can format this so that it only shows the vehicle name?
Controller:-
$mostPopularMake = Order::select('make')
->groupBy('make')
->orderByRaw('COUNT(*) DESC')
->limit(1)
->get();
View:-
{{ $mostPopularMake }}
Actual Output:-
[{"make":"Aston Martin"}]
its json format
Is that not what you wanted?
Are you blade tags in the middle of a view file or in an ajax response?
Hey @snapey
Json wasnt really what i was looking for. I was just looking for a clean output of the data.
Its in the middle of a view file:-
<h5><span class="badge badge-alt-success">{{ $mostPopularMake }}</span></h5>
Thanks in advnace.
Instead of get() use first()
$mostPopular = Order::select('make')
->groupBy('make')
->orderByRaw('COUNT(*) DESC')
->limit(1)
->first();
<h5><span class="badge badge-alt-success">{{ $mostPopular->make }}</span></h5>
Thanks @michaloravec. Thats partially sorted it. Its just the curly braces and quotes that remain. :/
What is your actual output?
Hey @michaloravec output is exactly as follows {"make":"Aston Martin"}
It's really weird that you get json. You can parse it with json_decode.
Like
<h5><span class="badge badge-alt-success">{{ (json_decode($mostPopular))->make }}</span></h5>
But this isn't normal.
What exactly you have in controller?
My thoughts exactly.
Currently this is the query in my controller:-
$mostPopularMake = Order::select('make')
->groupBy('make')
->orderByRaw('COUNT(*) DESC')
->limit(1)
// ->first(); Changed to Pluck
->pluck('make');
I changed to pluck instead of first which helped but didnt solve. This is currently the output using pluck ["Aston Martin"]
Do you have some casts on your model?
Hey @snapey i do indeed.
protected $casts = [
'product_id' => 'array',
'stage_id' => 'array'
'make' => 'string'
];
Add first() after pluck('make').
$mostPopularMake = Order::select('make')
->groupBy('make')
->orderByRaw('COUNT(*) DESC')
->limit(1)
->pluck('make')->first();
Aaaaahhh thank you :) thats sorted it. Why did it require ->first ontop of pluck in order to filter the data. Is it because it was in an array?
Really appreciate your help. Thank you both very much.
Yes, because it was array and with first() you get first item of array.
Makes sense. Cant believe i didn't think of that before. Thanks again. :)
Please or to participate in this conversation.