Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Flex's avatar
Level 4

how to count and get values table categoryname and display google charts in Laravel 5

working with laravel 5.6 and mysql db. I have table named as vehicles in my application like this,

id  name   categoryname
1   lki          Car
2   kio         Van
3   hytg      Car
4   hyu       Truck
5   htg        Van
etc

Now I am going count numbers of each categoryname as Car 2 Van 2 Truck 1

and display Google Chart using consoletvs/charts. I have one example to displaying existing all users in controller as,

class BarChartController extends Controller
{
    public function index()
    {
    $chart = Charts::database(Vehicle::all(), 'bar', 'google')
    ->elementLabel("Total")
    ->GroupByMonth();
        return view('charts.bar',compact('chart'));
    }
}

so, now I need new controller function to show above my requirement (show each categorynames in charts) how can I configure controller for it?

0 likes
6 replies
signar's avatar

@flex You could try something like this:

$categories = DB::table('vehicles')
  ->selectRaw('categoryname, COUNT(*) as categoryname_count')
  ->groupBy('categoryname')
  ->get();

Then you could loop over it like so:

@foreach($categories as $category)
    {{ $categoryname }} {{ $categoryname_count }}
@endforeach
Flex's avatar
Level 4

@signar it id occured following error

Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)
signar's avatar

@flex woops! :) I can't see where the mistake is. But I see another mistake, try this instead

@foreach($categories as $category)
    {{ $category->categoryname }} {{ $category->categoryname_count }}
@endforeach
Flex's avatar
Level 4

@signar accually google map called as following way in blade file,

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-heading">Google Chart Demo</div>

<div class="panel-body">
                    {!! $chart->html() !!}
                </div>
            </div>
        </div>
    </div>
</div>
{!! Charts::scripts() !!}
{!! $chart->script() !!}
@endsection
signar's avatar

@flex I don't know how to use the Google Charts package so that part you have to figure out for yourself. At least now you have the neccessary query to show total number of categories with this:

$categories = DB::table('vehicles')
  ->selectRaw('categoryname, COUNT(*) as categoryname_count')
  ->groupBy('categoryname')
  ->get();

You could try to replace Vehicle::all() with $categories

Flex's avatar
Level 4

No any better Solution?

Please or to participate in this conversation.