Support the ongoing development of Laravel.io →
Database Eloquent

I have no issues writing to my pivot table, but returning associations returns null

Schema:

 $table->integer('category_id')->unsigned();
 $table->foreign('page_id')->references('id')->on('pages');

  $table->integer('page_id')->unsigned();
  $table->foreign('category_id')->references('id')->on('categories');

Page model:


class Page extends Eloquent{
    public function pages(){

        return $this->belongsToMany('App\Category');

    }
}

Category Model:

class Category extends Eloquent{
   public function category(){
        return $this->belongsToMany('App\Page');

    }
}

CategoryController:

	public function index(Category $cat)
	{

        $category = $cat->find(2);

        return $category->pages;

	}

I want to return all pages with the category of id 2 (using my pivot table).

What i'm I doing wrong?

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

clayhenry clayhenry Joined 1 Dec 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.