O'Reilly logo

Learning Laravel's Eloquent by Francesco Malatesta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Inserting and updating related models

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();

The save() and associate() methods

Let's be clear; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required