Search code examples
phpmysqllaravelhas-many

How to hide empty categories in laravel


Hi Guys I have started building my first project using Laravel,

I have done a crash course on Laracast, learnt hasMany and belongTo however I am stuck at where I have categories which yet don't have any products. I don't have any sub categories I only want to show the categories which has some products and hide the empty one

So far I am getting my categories like this

$stocksCats     =   stockscat::isLive()->where('status', '=', 1);

my stocks class has looks like this

<?php

namespace App;

//use Illuminate\Database\Eloquent\Model;

class stock extends Model
{

public function scopeisLive($query) // With Scope
{

    return $query->get();

}

public function stockcat()
{

    return $this->belongsTo(stockscat::class);

}

public function stockgallery()
{

    return $this->hasmany(stockgallery::class);

}

}

and my stocks cat class looks like this

<?php

namespace App;

// use Illuminate\Database\Eloquent\Model;

class stockscat extends Model
{

public function scopeisLive($query) // With Scope
{

    return $query->get();

}

public function stocks()
{

    return $this->hasmany(stock::class);

}

}

Solution

  • Laravel provides a has() method (See docs) to check if an eloquent has a relationship. The following code snippet should be the solution:

    $stocksCats = stockscat::isLive()->has('stocks')->where('status', '=', 1);