Msoft
11 months ago
12
10
Laravel

How to print table column values count numbers with relationship table values?

Posted 11 months ago by Msoft

Hello, I have 2 models as Category and Vehicles with following relationship Category

 public function vehicles()
    {
        return $this->hasMany(Vehicle::class);
    }

Vehicle

 public function category()
    {
        return $this->belongsTo(Category::class);
    }

My vehicles table with following columns names,

id   number  categoryname
1     123           Car
2    589        Van
3    589        Car
4    563        SUV
5    563        Van

and categories table name as following

id   categoryname   images
1   Car             car.png
2   Van             van.png
3   SUV             suv.png
etc

Now I need count categoryname column values and print them in welcome.blade.php then I have Controller in VehicleController as following,

public function showcategoryname()
    {
      $names = Vehicle::groupBy('categoryname')->select('id', 'categoryname', \DB::raw('COUNT(*) as cnt'))->get();  

      return view('welcome')->withNames($names);
    }

in welcome blade view

 @foreach($names as $name)
    {{ $name->categoryname }} ({{ $name->cnt }})
@endforeach

it is working fine Now I need print as loop according to this values of categories table data as categoryname and Images etc..... then how can I print both two table data in a loop using above relationship?

Please sign in or create an account to participate in this conversation.