Tutorials , code & Inspiration

Inserting and updating related models in laravel 5.1


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...

prevChapter 1 of 10

Leave A Reply

Your email address will not be published.

Pin It on Pinterest