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

TimeSocks's avatar

Why isn't this pivot table set up working?

I have a table of events, and a table of categories. Each event can be in more than one category, and each category can have more than event. So I have set up a pivot table category_event, containing the category_ and event_ids to match them up. I have defined models for all 3 tables:

class Event extends Model {

    public function categories()
    {
        return $this->belongsToMany('App\Category');
    }

}

class Category extends Model {

    protected $table = 'categories';

    public function events()
    {
        return $this->belongsToMany('App\Event');
    }

}
class Category_Event extends Model {

    protected $table = 'category_event';

}

Then in my CategoryController I have a query:

$category = Category::with(['categories.events'])->where('id','=',$id)->get();

But this throws an error: Call to undefined method Illuminate\Database\Query\Builder::categories()

I initially thought the error might be down to how Laravel handles naming conventions of tables and models ending with 'y', so as you can see I have explicitly specified the name of the relevant table in the models. But I still get the error.

Any ideas? TIA

0 likes
3 replies
mstnorris's avatar
Level 55

Firstly you don't need to specify the table name, Laravel is smart enough to parse that and correctly set the table name for Category to categories.

Secondly, you don't need to have a class Category_Event. Try:

$category = Category::with('events')->where('id', '=', $id)->first(); // you don't need the "=" as this is the default

Also you can use the shorthand (magic method):

$category = Category::with('events')->whereId($id)->first();
1 like

Please or to participate in this conversation.