How to get data from third table in eloquent relationships eloquent many to many relationship

Viewed 540

I am using Eloquent ORM and I have Book model which connect to BookCategory model and BookCategory connect to Category. The l'm problem facing is how to include data from third table in eloquent relationships?

Book
    id
    name
    
Category 
    id
    name
    type
    
BookCategory 
    id
    book_id
    category_id
2 Answers

Lets say for example you want to get all the books of a certain category: assuming your pivot table name is Book_Category in your Category model:

public function books()
{
    return $this->belongsToMany('App\Models\Book', 'Book_Category', 'category_id', 'book_id');
}

and you can eager load category books like :

$categories = Category::get()->load('books');
//OR
$categories = Category::with('books')->get();
Related