PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How to hide empty categories in laravel

 October 21, 2022     has-many, laravel, mysql, php     No comments   

Issue

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);


Answered By - haidang
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing