How to query belongsToMany relationships in Laravel

Suppose we have Posts which belong to many different Categories. For this purpose we make three DB tables: posts (id, title), categories (id, name), and an intermediate one (posts_categories, with columns post_id and category_id).

The Post Model should be:

class Post extends Model
{
    use HasFactory;

    public function getCategories()
    {
        return $this->belongsToMany(Category::class, 'posts_categories');
    }

The Category Controller:

class CategoryController extends Controller
{

    public function index() {

        /*  
        *   Posts collection for a specific Category (e.g ID = 1) 
        *   from an intermediate column `posts_categories`
        */
        $posts = Post::whereHas('getCategories', function ($query) {
            $query->where('category_id', 1);
        })->get();

    }
    return view('welcome', compact('posts'));
}

You can also return posts collection with dynamic parameters:

// routes/web.php
Route::get('/{id}', [CategoryController::class, 'index']);

// Category Controller
class CategoryController extends Controller
{

    public function index($id) {

        /*  
        *   Posts collection for a specific Category (e.g $id) 
        *   from an intermediate column `posts_categories`
        */
        $posts = Post::whereHas('getCategories', function ($query) use ($id) {
            $query->where('category_id', $id);
        })->get();

    }
    return view('welcome', compact('posts'));
}

Leave a reply

Your email address will not be published.