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

Loriko's avatar

Pivot table problem

Hi, i'm not sure how to explain my problem but i'll give it a try.

I have 3 tables: pages, languages and language_page.

This is what my models look like: Page model:

public function languages()
    {
        return $this->belongsToMany('App\Language', 'language_page')
                    ->withPivot('title', 'content', 'slug', 'meta_title', 'meta_description')
                    ->orderBy('main', 'desc');
    }

Language Model:

    public function pages()
    {
        return $this->belongsToMany('App\Page')
                    ->withPivot('title', 'content', 'slug', 'meta_title', 'meta_description');
    }

What i want to do return a record from the page table where language_id is a certain id, and where slug is a certain text.

This is what i got so far:

Page::whereHas('languages', function($q) use ($language_id) {
                        $q->where('language_id', $language_id);
                    })
                    ->get();

My problem: how can i add a where clause with the column slug (from the pivot table language_page) ?

i hope this makes any sense at all..

0 likes
4 replies
jekinney's avatar

According to the code above your storing to much data in your pivot table. A pivot tables purpose is link to tables together, generally with only two columns that reference the primary key for each table ( basic pivot table) not to store all the data you have set in your withPivot().

Revise your schema and try again. If your pivot table doesn't have that data your accessing the pivot table wrong.

Loriko's avatar

Alright, good to know i've been using it wrong. Thank you :) I'll fix it when i have more time.

Though, do you know a way to make it work this way?

Loriko's avatar

i did some digging, and this is what i have so far:

Page::with(['languages' => function($q) use($language_id, $slug) {
                        $q->where('language_id', $language_id);
                        $q->wherePivot('slug', $slug);
                    }])
                    ->first();

Though the output of this is the first record of the page table. (instead of the the one that it should return)

And SQL generates this: "select * from pages", as if it ignores everything inside the with?

jekinney's avatar

The laravel docs are really good about pivot tables. Set up your relationships (belongsToMany) and all you need to do is query like Page::with('languages')->where('slug', $slug)->first(). But if your intention is a page slug links to many languages then no need for a pivot table, be cause that is a one to many not many to many.

Please or to participate in this conversation.