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

nickdavies07's avatar

Accesing data from base tables and pivot tables

Cannot get my head round this one.

I have the following:

  • schools (id, name)

  • categories (id, name)

  • types (id, name)

  • Schools can have many Categories and vice versa (pivot as category_school) - (id, category_id, school_id)

  • Types can have many Categories and vice versa (pivot as category_type) - (id, category_id, type_id)

I'm trying to get the data from all tables so I can populate a dropdown select box based on the chosen School and Type. So if a user selects School A, then Type C, all the categories should list for School A and Type C.

Can't figure out how I would access the all the data to be able to do this. So far all I've been able to do is something like $categories = Type::find(request('type'))->categories; to get the categories based on the type requested.

Screen grab of select boxes. https://pasteboard.co/HDHjtey.png

0 likes
3 replies
maurojunior2011's avatar
Level 1

I'm on the street now, but a quick fix until you find a better one:

1 - Pick up all school categories 2 - Take all type categories 3 - Make the intersection between the collections

1 like
yordanovbg's avatar

Try something like this

Category::whereHas(['schools' => function($query) {
    $query->where('category_school.school_id', request('school_id'));
}])
    ->whereHas(['types' => function($query) {
        $query->where('category_type.type_id', request('type_id'));
    }])->get();

nickdavies07's avatar

@maurojunior2011 Thanks! I did the following and it works great.


$school = School::find(request('school'))->categories;
$type = Type::find(request('type'))->categories;

return $school->intersect($type);

Returns a beautiful collection with both collections combined, omitting any values not present in both.

1 like

Please or to participate in this conversation.