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

depape's avatar

Help with Eloquent model / relationship

I was reading through documentation, but I can't figure out what kind of model/relationship I should use in following example:

I have 3 tables: books, publishers and books_publishers with following fields:

books: book_id, book_title, book_author...

publishers: publisher_id, name, adress...

books_publishers: book_id, publisher_id

How should I define my models to also get publishers details when I'm doing query on books table?

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

You would have a belongsToMany relationship between Book and Publisher using the books_publishers pivot table. You have used a non-conventional name for the Pivot table, so you will need to specify this inside the relationship definition.

// Book
public function publishers
{
    return $this->belongsToMany(Publisher::class, 'books_publishers');
}

Then you can eager-load the publishers when you are querying for books:

// Eloquent query
$books = Book::with('publishers')->get();

Is it expected that books can have more than one publisher?

depape's avatar

Thank you. I used your example and it works ok, I just had to add local and foreign keys to relationship definition.

Thanks again!

tykus's avatar

No worries. You can mark the best answer above to close the topic

Please or to participate in this conversation.