Laravel

Laravel 5.6 Eloquent ORM Tutorial with CRUD Example

January 30, 2018

author:

Laravel 5.6 Eloquent ORM Tutorial with CRUD Example

Laravel provides Eloquent ORM (Object Relational Mapper) which is immensely powerful. Eloquent utilizes Active Records. It is a scenario where an object maps with a table of a database on a one-to-one basis. While the properties of objects correspond to the column fields of the table in the same way. If you are familiar working with Objects in PHP, chances are- you already know how to work with eloquent. These objects are called Models in terms of Eloquent.

# What is Laravel Model?

Since we already learned about Query Builder, it is the right time to step up the knowledge. As we have seen earlier, according to MVC (Model View Controller) pattern, a model is responsible for managing and maintaining the data of an application.

Every database table can correspond to a Model which can then be used to interact with that table. We can also use a combination of multiple models to retrieve the desired complex result. Laravel Model allows querying the database table as well as insert fresh records in the table. Models are stored in App directory of the application.

Remember we already tried querying a database in Query Builder section? We didn’t have to create Models at that moment as we utilized DB class then. Laravel provides DB class right out of the box. But since we now want to use Eloquent, we need to first generate a model with artisan command:

php artisan make:model Post
# app/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
}

Note that we first need to create a relevant migration table and then its model. Also, migration and database table have a plural form such as Posts, Users, etc. while respective models have singular form in their name like Post, User, etc. This isn’t a coincidence but intentional in Laravel for their inter-mapping. Talking about migrations, we can also generate a migration while creating the model with an optional flag --migration or --m:

php artisan make:model Post --migration

OR

php artisan make:model Post -m

# What is Laravel Eloquent ORM?

Imagine Eloquent as a polished form of Query Builder which eliminates the need to mug up the queries and can be simply remembered based on logic. We have now set the stage to retrieve data from the database.

# CRUD Operations using Laravel Eloquent ORM with Example

Here are some instances of CRUD operations:

# Insert (Create)

We can insert a new record in the database by creating a new instance of the model in the controller and then calling save method:

# Controller

use App\Post;
...
public function store(Request $request)
{
   $post = new Post;
   $post->title = $request->title;
   $post->content = $request->description;
   $post->category = $request->category;
   $post->save();
}

Though we can insert static data from the controller but that’s rarely a case. So, above is the example to store dynamic data from incoming HTTP Request which we assign to respective database table (or model) column. It is important to call save method at the end to store the data in the database.

# Retrieve (Read)

There can be multiple use cases to retrieve data as we may need to read all the database rows or a specific one. Let us see each of them here:

Retrieve all the data:

# Controller

use App\Post;
...
public function index()
{
  $posts = Post::all();

  foreach ($posts as $post) {
      echo $post->title . '<br>';
  }
}

Retrieve single model:

# Controller

use App\Post;
...
public function show($id)
{
    // Retrieve a model by its primary key...
    $post = Post::find(3);
    echo $post->id . '<br>';


    // Retrieve the first model matching the query constraints...
    $post = Post::where('id', $id)->first();
    echo $post->id;
}

Retrieve aggregates:

$count = App\Post::where('category', 'laravel')->count();
$max = App\Post::where('category', 'laravel')->max('views');

# Update

The save method can also be used update records that already exist in the database. All we need to do us retrieve the attributes and set new values to it:

# Controller

use App\Post;
...
public function update(Request $request, $id)
{
    $post = Post::find(3);
    $post->category = 'PHP';
    $post->save();

}

Conclusion:

We just witnessed one of the best features of Laravel – The Eloquent ORM. We started with What is Model in Laravel and Eloquent ORM. We then also used Eloquent to perform Database CRUD operations. Eloquent provides a special delete operation. In the coming section, we will see both the basic and these special delete operations.

Questions & Comments:

Thank you for reading. Hope you found this tutorial useful. If you encounter any error while performing any queries discussed here, feel free to share them in the comment section below.

Leave a comment

Your email address will not be published. Required fields are marked *