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

mozew's avatar
Level 6

How to show display categoory_id = id

I want to display categories where categoory_id = id

Controller

public function index ()
{
    $id = 1;
    $webDesigns = About::with(['categories' => function($q) use ($id) {
        $q->where('category_id', $id);
    }])->get();
    return $webDesigns;
    $webDesigns = About::with(['categories' => function($q) { $q->where('id', 1); }])->get();
    $developers = About::with(['categories' => function($q) { $q->where('id', 2); }])->get();
    $graphics = About::with(['categories' => function($q) { $q->where('id', 3); }])->get();
    $computers = About::with(['categories' => function($q) { $q->where('id', 4); }])->get();
    return view('Home.index', compact('webDesigns', 'developers', 'graphics', 'computers'));
}

Model

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

Table(s)

Schema::create('about_category', function (Blueprint $table) {
    $table->integer('about_id')->unsigned();
    $table->integer('category_id')->unsigned();

    $table->foreign('about_id')->references('id')->on('abouts')->onDelete('cascade');
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});

Schema::create('categories', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

Schema::create('abouts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->text('body');
    $table->timestamps();
});

How to this work? OR What am I missing?

0 likes
5 replies
Snapey's avatar

you want to display EVERY About model but only include category 1 child models?

Snapey's avatar

And what do you get with the above code?

mozew's avatar
Level 6

We have three blocks

Block

And three categories:

  • Important Links
  • Userful Links
  • Get in touch

I want to display Userful Links in block when select and save Userful Links category.

Snapey's avatar

cant help if you cannot understand the question

Please or to participate in this conversation.