Laravel Eloquent ORM - Eight basic eloquent you need to know

Laravel provides built-in eloquent and allows you to easily create or update the table record base on conditions also it’s come with a sync method to more easily construct many-to-many relationship data. The following article will walk you through the important eloquent method that you need to know. 

1. Get

The get function will get all records from the specific table as defined in the model and return a instance of eloquent collection.

Article::get();

2. Find

The find function will get the specified record by id from the specific table as defined in the model and return a data record.

Article::find(1);

3. FindOrFail

The findOrFail method will do the same functionality as the find method but if the record is not found it will throw an Illuminate\Database\Eloquent\ModelNotFoundException basically 404.

Article::findOrFail(1);

4. Create

The create method accept the array with key value it will create new record.

Article::create(['title' => 'Article', 'content' => 'Content']);

5. Update

The update method allow you to update specific record base on the model instance you get this example will update the record by id.

Article::findOrFail(1)->update(['title' => 'Article', 'content' => 'Content']);

6. Delete

Delete is the same as the update function it will delete any specific record or base on a model instance that you get with.

Article::findOrFail(1)->delete();

7. UpdateOrCreate

The first parameter will check if the related associate array exists in database update the record with the second parameter. If the related associate array not exists in the database create a new record with a combination of first and second parameter.

Article::updateOrCreate(
    ['title' => 'Article'],
    ['content' => 'Content']
);

8. Sync

The sync method uses to create records for many to many relationships. For example, you have an article that each article can have many tags also a tag can have many articles as well so we need to create a new table example article_tags to store the relation between the article and tag.

In the article model tie the relation to the tag so that we can use sync.

public function tags()
{
   return $this->belongsToMany(
       Tag::class,
       "article_tags",
       'article_id',
       'tag_id'
   );
}

The below code will store records in the article_tags table with the article_id of 1 and the following tag_id 1, 2.

article_tags

| article_id | tag_id |
| 1          | 1      |
| 1          | 2      |


$articleObj = Article::findOrFail(1);
$articleObj->tags()->sync([1, 2]);

Conclusion

After going through the above article step by step you will have a good understanding of the basic Laravel eloquent that you will need to use in your daily Laravel project.

What method that you use that not include in the above content? In which condition?