Home > OS >  get all results by pivot table id, laravel
get all results by pivot table id, laravel

Time:01-02

i have laravel many to many relationship enter image description here

enter image description here

and i want to get all advertisements, with category id, example 1, in controller

whats wrong? how to get all models, by pivot table categories_id = 1?

    $category_details = Categories::where('slug','=', $category_slug)->first();

    $advertisements = Advertisement::with(['categories'=> function($query){
        $query->wherePivot('categories_id', $category_details->id);
    }])->get();

and i get this error

CodePudding user response:

You must pass $category_details variable to Closure

$advertisements = Advertisement::with(['categories'=> function($query) use($category_details) {
        $query->wherePivot('categories_id', $category_details->id);
    }])->get();

CodePudding user response:

I think it would be a good idea to rename the Categories model of yours to a singular form and add a similar relationship to it:

class Category extends Model
{
    public function advertisements()
    {
        return $this->belongsToMany(Advertisement::class);
    }
}

Then you can simply do this:

$category = Category::where('slug','=', $category_slug)->firstOrFail();

return $category->advertisements()
    ->with('categories')
    ->get();

Or you can make it a bit fancier:

return Category::where('slug','=', $category_slug)
    ->firstOr(fn() => Category::make())
    ->advertisements()
    ->with('categories')
    ->get();

  • Related