Until now, you have learned how to define relationships and query them, in order to get data from related models. However, you can also insert and update related models in an easy way.
Let's pick a really basic example to get started: imagine that we are adding a new book (Michael Strogoff, Jules Verne). We have to specify some details as follows:
$book = new Book; $book->title = 'Michael Strogoff';
Then, we specify the correct author ID:
$author = Author::where('first_name', '=', 'Jules')->where('last_name', '=', 'Verne')->first(); $book = new Book; $book->title = 'Michael Strogoff'; // other data... $book->author_id = $author->id; // and finally... $book->save();
Let's be clear; ...