push notification with laravel

Its sure; this works really well. However, it is not the best way you can do it. In fact, with Eloquent, you can work with related models using some other specific methods.

Let’s rewrite this example using the method save() on a relationship. Also, we will use an associative array as a constructor argument in order to assign attributes.

  $author = Author::where('first_name', '=', 'Jules')->where('last_name', '=', 'Verne')->first();

  $author->books->save(new Book([
    'title' => 'Deven rathore',
    // other attributes...

Done! It only took a couple of instructions. The save() method will automatically set the author_id key for the book you just passed as a parameter.

However, this is not just a time-saving trick; if you read the code carefully, you will note that we are actually creating very readable code. Instead of setting external keys, treating the relationship in a more physical way, we are saving the book as an element of the collection of books for a certain author. Quite different!

You can also do the same thing with arrays of objects, using the saveMany() method:

  $author = Author::where('first_name', '=', 'Jules')->where('last_name', '=', 'Verne')->first();

    new Book(['title' => 'dune book']),
    new Book(['title' => 'The Mysterious Island']),
    new Book(['title' => 'Off on a Comet'])

As mentioned before, the saveMany method will set the external author_id key for every Book instance passed in the array. You can also update an existing relationship, changing its association with another model.

In this case, you must use the associate() method. Take a look at this example:

  $wrongAuthor = Author::where('first_name', '=', 'Jules')->where('last_name', '=', 'Verne')->first();

  $wrongAuthor->books->save(new Book([
    'title' => 'The Alchemist'

  // oops! wrong author!

  $book = Book::where('title', '=', 'The Alchemist')->first();
  $rightAuthor = Author::where('first_name', '=', 'Paulo')->where('last_name', '=', 'Coelho')->first();

  // done!

What happened? In the first part of the example, I assigned The Alchemist to Jules Verne. After one year of penitence in the desert, I came back to get the right author (by using the $rightAuthor variable), and then using the associate() method on the books relationship.

The first passed parameter is the model instance you want to work with.


So, the rule is quite simple: use the save() method when inserting a new record or the associate() method in order to update an existing record.