Everything that you need to know about Laravel’s Eloquent ORM


While moving with the trends in technologies of web applications & having a wide range of back end developers with great experience in respective technologies, let us have an overview about the Laravel’s Eloquent ORM in this article.

Laravel provides the eloquent ORM for working with your database. This is a simple and useful feature in Laravel. Today we’ll look at how we can use Eloquent to interact with our database and do:

This is how Eloquent works:

In Eloquent ORM, each database table is having corresponding model for interacting with table. This means that each model you create in your MVC structure corresponds to a table in your database. By using this model you can perform database table related operations like select, insert, delete, update records from tables.

Let’s define a Model:

Let’s create an eloquent model. As you might know that Models are typically located in the app directory.

Eloquent models are models that extend the Illuminate\Database\Eloquent\Model class. In the MVC architectural design, models are used to interact with data sources.

You can also create model from artisan command,

php artisan make:model Student

After executing the command create model in /app/Student.php

You will get a file like this one,

namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { // } 

Defining Table Name in Model:

As every table will be having its own model, it’s obvious that you will need to define the table name in the model. So, while defining the table name in model, plural name of the class should be used as given below (which will be used as the table name unless another name is explicitly specified):

protected $table = ‘students’

Timestamps

Timestamps feature in Eloquent is time saving. You don’t need to add it explicitly, it automatically handles the database operations for created_at & updated_at fields. Only the thing you need to take care of is, you should have these fields in your table.

In case you don’t want these fields to get updated automatically, then you just need to set $timestamps property to false in your model to like,

public $timestamps = false;

It is as simple as that.

In order to set date format, initialize $dateFormat with any format that you want. For example,

protected $dateFormat = ‘U’;

Connecting with database:

Eloquent model uses default database connection to configure your application. If you want to use specific connection then use $connection property as given,

protected $connection = ‘connection-name’;

Retrieving Models:

Once your model is complete, you are ready to insert or retrieve data from table. Each Eloquent model provides powerful query builder for quick execution of query.


namespace App;
class Student extends BaseModel {

protected $primaryKey = 'id';

protected $table = 'students';

protected $fillable = array('name', 'standard', 'roll_no');

}

protected $fillable = array(‘stud_name’, ‘stud_address’, ‘stud_marks’);

You can insert or update the fields in $fillable array.

Below is the code which includes model in controller and performs database related operations.


<?php namespace App\Http\Controllers; use App\Student; use Illuminate\Http\Request; use App\Http\Controllers\Controller;gvb class StudentController extends Controller { /** * Create a new Student instance. * * @param  Request  $request * @return Response */ public function insert_student_data(Request $request) { // Validate the request... $student = new Student; $student->name = $request->name;

$student->save();

}

/**

* Update a new Student instance.

*

* @param  Request  $request

* @return Response

*/

public function Update_student_data(Request $request)

{

// Validate the request...

$student = App\Student::find(1);

$student->stud_name = 'New student Name';

$student->save();

}

/**

* Update a new Student instance.

*

* @param  Request  $request

* @return Response

*/

public function Delete_ Student (Request $request)

{

// Validate the request...

$student = App\Student::find(1);

$student->delete();
}

}

Soft Deleting

Soft deleting is a much needed functionality in every platform. But Eloquent ORM provides it’s own soft delete functionality. When models are soft deleted then records are not actually removed from your database. If model has non-null deleted_at value, the model has been soft deleted. To enable soft delete use the Illuminate\Database\Eloquent\SoftDeletes trait on the model and add the deleted_at column to your $dates property:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

class Student extends Model{

use SoftDeletes;

/**

* The attributes that should be mutated to dates.

*

* @var array

*/

protected $dates = ['deleted_at'];

}

Eloquent Querying Relationships

One to One Relationship

One to one relationship are defined in eloquent model. For example a Student model be associated with one City. To define relationship, we place a City method on Student model. The City method should call has One method and return result:

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { /** * Get the city record associated with the student. */ public function city() { return $this->hasOne('App\City');
}
}

The first argument passed to the hasOne method is the name of the related model. Once the relationship is defined, we may retrieve the related record using Eloquent’s dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:

$city = Student::find(1)->city;

Eloquent determines the foreign key of the relationship based on the model name. In this case, the City model is automatically assumed to have a stud_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method:

return $this->hasOne(‘App\City, ‘foreign_key’);

One To Many

A “one-to-many” relationship is used to define relationships where a single model owns any amount of other models. For example, a student may have multiple number of subjects. Like all other Eloquent relationships, one-to-many relationships are defined by placing a function on your Eloquent model:

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { /** * Get the subjects for the student. */ public function subjects() { return $this->hasMany('App\Subject');
}
}

Once the relationship has been defined, we can access the collection of subjects by accessing the subjects property. Remember, since Eloquent provides “dynamic properties”, we can access relationship methods as if they were defined as properties on the model:

$subjects = App\Student::find(1)->subjects;
&nbsp;
foreach ($subjects as $subjects) {
//
}

Many To Many

Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of such a relationship is a student with many teachers, where the teachers are also shared by other students. For example, many students may have the teacher of “English”. To define this relationship, three database tables are needed: student, teacher, and role. The role table is derived from the alphabetical order of the related model names, and contains the student_id and teacher_id columns.

Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method. For example, let’s define the roles method on our Student model:

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { /** * The roles that belong to the user. */ public function roles() { return $this->belongsToMany('App\Role');
}
}

This is how Eloquent ORM can be implemented. Hope it was easy learning about Eloquent ORM. Feel free to ask any queries to our back end developers by commenting on the blog post.

Everything that you need to know about Laravel’s Eloquent ORM was last modified: March 14th, 2017 by Shailesh K

One thought on “Everything that you need to know about Laravel’s Eloquent ORM

  1. Hey,
    I recently had the good fortune of seeing your post regarding “Everything that you need to know about Laravel’s Eloquent ORM”. It is intelligently written and, includes sound, practical guidance with valid facts and figures. I look forward to reading your next useful write-up.
    Thank you.
    Jessica

Leave a Reply

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