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

Tachi's avatar
Level 1

belongsTo relationship not working as it should?

I have this relation in my model:

class Product extends Model
{
    protected $fillable = [
        'id', 'title', 'description', 'main_image', 'price', 'category_id', 'in_stock', 'ammount', 'status', 'quatable', 'images'
    ];

    public function enabled_category()
    {
        return $this->belongsTo('App\Categories', 'category_id')->where('enabled', 'yes');
    }

}

And I'm trying to get product that belong to categories that are enabled, where enabled == yes

So i'm getting them like this:

 $products = Product::with('enabled_category')->get();

But i still get products with disabled categories, where categories.enabled == 'no'

In my phpdebugbar I only see this 2 queries being called:

select * from `products`

select * from `categories` where `enabled` = 'yes' and `categories`.`id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49')

And I still get all the products, even those with disabled category.

Why is this happeining and how I can get products that belong only to enabled categories?

0 likes
1 reply
cipsas's avatar
cipsas
Best Answer
Level 10

Your query

$products = Product::with('enabled_category')->get();

tells, that fetch all products, and eager loading enabled categories. you should use whereHas:

$posts = Product::whereHas('categories', function ($query) {
    $query->where('enabled', 'yes');
})->get();
class Product extends Model
{
    protected $fillable = [
        'id', 'title', 'description', 'main_image', 'price', 'category_id', 'in_stock', 'ammount', 'status', 'quatable', 'images'
    ];

    public function categories()
    {
        return $this->belongsTo('App\Categories', 'category_id');
    }

}
1 like

Please or to participate in this conversation.