The Top Features of Eloquent, Laravel’s ORM

Eloquent Object Relational Mapper (ORM), which is packaged with the famous PHP framework Laravel, presents an elegant, beautiful, and very efficient way of communicating with the database. Websites are getting more complex due to various customization, so developers need to create a complex database. Laravel Eloquent provides a very easy way to manage all development-related problems. It provides the freedom to write well-formatted, easy to read, sustainable, and well-documented code. With so many features it is one of the reasons behind Laravel’s success.

In this article, we are going to cover some of the most prominent features of Eloquent ORM. Here are the topics which we will be covering in this article:

What is Eloquent ORM?

Laravel eloquent ORM comes with the Laravel framework to provide an easy, hassle-free, and simple way to work with a database. Some of the features due to which it is famous are Soft deleting, Timestamps, ActiveRecord implementation, multiple database handling, eager loading, model observers, model events, and much more. Eloquent relationships are the same as the method in Eloquent model classes. Relationships are powerful query builders when defined as methods help in method chaining and powerful query capabilities.

How does Eloquent ORM work?

Eloquent ORM is famous for its active record implementation for working with databases. Active Record is an architectural pattern in which each model made in MVC architecture corresponds to a table in the database. You can easily create relation data in your database and work with the Object-Oriented model with the help of eloquent. SQL queries are so tedious and time taking when it comes to code. Laravel Eloquent gives you the freedom to do common database operations without lengthy SQL queries. Models have made insertion, update, deletion, and synchronizing multiple databases very easy. You have to just define database tables and the relation between them and your work is done.

Getting started with Eloquent

Laravel comes with an inbuilt command-line interface, which is called Artisan Console. Driven by the symphony control component, it provides an easy way to use the command line during the development phase of the app.

Before going further in this article configure the database connection in config/database.php.

Before getting started with the Eloquent model first, verify you have installed the Laravel or not. If you have not then you can download it from getcomposer.org

If you want to see the list of available commands in Artisan type the following command:

php artisan list

After that, all commands with a short description will be available on your screen. If you want help with some of the commands then just type the command with “help” written before it. Example:

php artisan help migrate

Creating Eloquent models

Before doing anything you have to create a model in the database. Models help you in seeding, bathing, etc. It is the model that communicates with the database. It also allows you to query in your database and seed it with data. Model is typically stored in app\Models directory the reason being just for the sake of well-documented code. We prefer this practice too but it’s totally your choice, the only condition is that it should be auto-loaded according to your composer.json file. All Eloquent models extend Illuminate\Database\Eloquent\Model class. The basic command for creating models is `make:model` Artisan command:

php artisan make: model Student

The basic syntax for defining a model is:

class User extends Model {}

Database migration can also be generated during the creation of the model just by adding the `-m` or `-migration` parameter in the previous command.

php artisan make:model Student--migration   
php artisan make:model Flight -m

Seeders, factories, controllers, and various types of classes can be generated by passing suitable parameters to `make:model` Artisan command. Examples are given below:

php artisan make:model Flight --factory
php artisan make:model Flight -f

php artisan make:model Flight --seed
php artisan make:model Flight -s

php artisan make:model Flight --controller
php artisan make:model Flight -c

Moreover, these commands can be combined to create multiple classes at once.

php artisan make:model Flight -mfsc

Some of the basic model convention that we should keep in mind:

Updating and deleting elements

Updating

To update a model you have to retrieve it, change the attribute you want to change, and then call the save method. The `updated_at` property will automatically be changed so need to change it manually.

$student = Student::find(1);

$student->email = ‘xyz@example.com';

$student>save();

Bulk updates can also be done for multiple models that match a given query.

Deleting an existing model

For deleting a model simply call the delete function:

$student = Student::find(1);

$student>delete();

Deleting by key:

Student::destroy(1);

Student::destroy([1, 2, 3]);

Student::destroy(1, 2, 3);

You can also perform delete on the basis of some query.

$affectedRows = Student::where('votes', '>', 100)->delete();

Related model

In any database, there can be related models. When two or more models rely on each other for value then they are called related models. For example, if you want to add a new comment to a post then instead of updating post_id manually you can directly update from and its parent model

$comment = new Comment(['message' => 'A new comment.']);

$post = Post::find(1);

$comment = $post->comments()->save($comment);

Associate models

These models can be used to update models using the associate method, it will set a foreign key on the model. You may also relate models having many to many relations.

Model Events

Whenever we want to tap into various stages of a model’s life cycle like saved, update, or deleted, an event is fired called Model events. Various events are saved, deleted, updating, deleting, updated, restoring, restored. For example, when you are inserting a new item, the creating/created event is fired, but if the item is not new then uploading/uploaded is fired.

Canceling Save operation via an event

If the event is returning false then the action will be canceled. The events can be anything such as delete, update, create, delete.

Student::creating(function($student)
{
    if ( ! $student>isValid()) return false;
});

How to register event listeners  

Like in every language an event needs a service provider to get registered, here also EventServiceProvider which serves as a location to register model event bindings.

Example:

public function boot(DispatcherContract $events)
{
    parent::boot($events);

    Student::creating(function($student)
    {
        //
    });
}

Model Observers

Model Observes help us in handling model events. An observer class may have methods corresponding to various model events.

class StudentObserver {

    public function saving($model)
    {
        //
    }

    public function saved($model)
    {
        //
    }

}

Another way of registering  an observer method is with the help of the observe method

User::observe(new UserObserver);

Generating Model Urls

Model URLs correspond to the unique url form by passing the model to route or action method. When a model is passed to the route or action method, its primary key is inserted in the URI.

Route::get('student/{student}', 'StudentController@show');

action('StudentController@show', [$student]);

Here, the student id will be inserted in the url. If you would like to replace another property in the generated URL, you have to override the getRouteKey method in your model.

public function getRouteKey()
{
    return $this->slug;
}

More Laravel Eloquent Features

Convert to arrays/JSON

Whenever you are building an API result is most likely to be in JSON, due to which you have to convert your relationships in JSON/array. Laravel Eloquent serves this purpose also. To convert model relationships into an array you can toArray() methods.

$student = Student::with('roles')->first();

return $student->toArray();

For converting an entire collection of a model into an array, the following methods can be used:

return Student::find(1)->toJson();

Now we will see how to return a model from the route. Whenever a model is converted into a string, it will be converted to JSON, so you can return Eloquent objects directly from routes.

Route::get('student', function()
{
    return Student::all();
});

Some protected numbers like `personal_id` or password need to be hidden or protected. To do this you have to add `$hidden` property in your model;

Attribute casting

If you want to convert the data type of a variable one option you have is to use a mutator for each of the attributes which can be time-consuming and lead to bugs. Another option is that you have to use the casting method for the particular variable. You can add the attribute to the cast the property of your model. Other acceptable cast types are integer, float, double, real, object, string, array.

Here is an example.

protected $casts = [
    'is_student' => 'boolean',
];

In this example even if is_student has a different datatype but when you will access it will be returned as a boolean.

The array cast is very helpful when you have to work with a database column of type serialized JSON. Serialized JSON means encoding an object into a string. If one of your columns has serialized JSON then after implementing array cast will automatically convert it to PHP array, when you fetch it in your eloquent model.

protected $casts = [
    'options' => 'array',
];

Date Mutators

Carbon is an international PH extension of DateTime. Eloquent concerts the created_at and updated_at attribute to Carbon which has various helpful methods and extends PHP DateTime class. Easy customization is available if you don’t want automatic mutation. You just have to override the getDates class. To disable date mutation completely just return an empty array in `getDates` method. An example is given below:

public function getDates()
{
    return ['created_at'];
}

If a column is considered as the date you have four choices, either you have to value a UNIX timestamp, date string(Y-m-d), date-time, and DateTime/Carbon instance.

Accessors and Mutators

Just like getting and setting values in any language, accessors and mutators help to format Eloquent attributes before retrieving or setting them on model instances. The difference between accessors and mutators is that accessors are used for fetching the data whereas mutators are responsible for changing the data.

For defining an assessor simply call `getFooAttribute` on your model, but the nomenclature of the method should follow camel-casing no matter if column-name is in a small case.

class User extends Model {

    public function getFirstNameAttribute($value)
    {
        return ucfirst($value);
    }

}

Defining a mutator can be done in the same fashion just use `setFooAttribute` and yes again camel casing should be followed.

class User extends Model {

    public function setFirstNameAttribute($value)
    {
        $this->attributes['first_name'] = strtolower($value);
    }

}

Soft Deleting

Soft Delete does not mean deleting from the database but a separate timestamp `deleted_at` is added corresponding to the record. You can perform soft delete in your model by applying the SoftDeletes property to the model. 

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model {

    use SoftDeletes;

    protected $dates = ['deleted_at'];

}

softDeletes method can be used to add deleted_at property from migration. Migration is nothing but managing your database in PHP rather than SQL.

$table->softDeletes();

In some cases, you may want to show soft deleted results when you call a query. To achieve this you can use withTrashed method in the query.

If you want to show only soft deleted models in results, then use the onlyTrashed method.

$student = Student::onlyTrashed()->where('account_id', 1)->get();

After so much operation if you want soft deleted models back into active mode, then use the restore method.

$student->restore();

restore method can also be used in the query directly.

Student::withTrashed()->where('account_id', 1)->restore();

Now after soft delete if you want to permanently delete the model from your database, then use forceDelete method

$student->posts()->forceDelete();

To verify if a model is soft deleted or not you can use trashed method.

if ($student->trashed())
{
    //Todo
}

Conclusion

Laravel is one of the most famous frameworks in PHP. Laravel eloquent provides a very easy way to communicate with databases. In this article, we have covered some of the important features of Laravel’s Eloquent. There are much more features of Eloquent, you can learn about them here. Follow the link and discover all the awesome features of Laravel Eloquent.