Q:

Laravel: Create a new record in a has many relashionship

I have the following tables

Users

id

Books

id

favourite_books

id
user_id (FK)
book_id (FK)

In my models I have the following:
class User {
    public function favouriteBooks()
    {
        return $this->belongsToMany(Book::class, 'favourite_books');
    }
}

class Book {
    public function usersFavourited()
    {
        return $this->belongsToMany(User::class, 'favourite_books');
    }
}

How do I create a new book that a user has favourited? In other words,what is the Laravel way in creating a new row in the favourite_books table.

A:

In the Laravel documentation under many to many relationships ( https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships ) it shows the following:
$user = App\User::find(1);

$user->roles()->attach($roleId);

In your case roles() would be the relationship method for books on your user model (favouriteBooks()) and $roleid would be the id of the book being favourited.

