Steve
Steve

Reputation: 645

Laravel return model with if statement

I'm trying to create offers and assign them to parent categories, to be more specific i have an Offer model and inside the offer model i have this many to many relationship

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

I want the above function to return ONLY the categories which have NULL parent_category which mean they are the parent categories. Is it possible with the above code?

Upvotes: 0

Views: 675

Answers (2)

Nuno Peixoto
Nuno Peixoto

Reputation: 154

Without knowing the entire scope of your project, I'd suggest one of the following: either change the name of the relation (A) or keep the relation as is and query it when you need it (B).

Option A -

public function childCategory() {
    return $this->belongsToMany(Category::class)->whereNull('parent_category');
}

Option B -

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

$offer = Offer::with('category')
    ->whereHas('category' function ($query) {
        $query->whereNull('parent_category');
});

Upvotes: 2

Alex Black
Alex Black

Reputation: 462

public function category() {
    return $this->belongsToMany(Category::class)->where('parent_category', null);
}

Upvotes: 0

Related Questions