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...
  $book->save();

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares