What is Eloquent And How to Implement it in Laravel?

Eloquent is a very interesting concept in Laravel. It is Laravel’s flagship database tool out of the box which is built using Laravel Query builder. It is easy to understand and use for any developer. Basically Eloquent is an “ActiveRecord” ORM, which means it is a single abstraction layer to deal with multiple types of databases. It means Eloquent doesn’t case which type of databases you are using or how many are there. It’s implementation is simple and consistent with all of them. But we will implement all of that not just in theory. We will code that so let’s star that. Let’s start with a simple migrations to create contacts table. In this table we will have name, email and phone number.

Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('phone_number');
            $table->timestamps();
 });

We will make a contactFactory to create fake contacts to use in our project. We can do that by running this command.

php artisan make:Factory ContactFactory

Then we will add this code in our ContactFactory.

use Faker\Generator as Faker;

$factory->define( \App\Contact::class, function ( Faker $faker ) {
	return [
		'name'         => $faker->name,
		'email'        => $faker->email,
		'phone_number' => $faker->phoneNumber,
		'created_at'   => now(),
		'updated_at'   => now(),
	];
} );

Then we will create our ContactsSeeder by running this command.

php artisan make:seeder ContactsSeeder

After that we need to create our model using this command.

php artisan make:model Contact

And we will place this code in Contact model.

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{

	protected $fillable = ['name', 'email', 'phone_number'];

}

Here you should note that we are using Illuminate\Database\Eloquent\Model class. This class holds the key to all the operations and methods. This class has all the methods which we will call later like create, save, delete, where and many more. This class interacts with our database and we are telling it that we want to fill only name, email and phone_number when we will call create method or during mass insert. If we will pass array to create method then every other index of that array will be ignored but only these fillable will be regarded and inserted in contacts table.

Then we will put these lines of code in ContactsSeeder to create 50 fake contacts.

factory( \App\Contact::class, 50 )->create();

Then last but not the least we need to run this command so that our Laravel installation knows about ContactSeeder.

composer update -o

Then we will run this command to add records in contacts table.

php artisan db:seed --class=ContactsSeeder

Now this part has a very little to do with our main thing. Remember? Eloquent. But let’s eat the main course now.

Just write this line in Your HomeController and dd() the results.

$contacts = Contact::all();

Yes you can get all the records just by using Contact::all() method. Easy?

Let’s find a record which has an ID = 10.

$contact = Contact::findOrFail( 10 );

Simple? Now if we want to do a where query on contacts table then we need to do this.

$contact = DB::table( 'contacts' )->where( 'email', '=', '[email protected]' )->first();

But using eloquent we can do this by using Contact class which implements eloquent/model as I told you earlier.

$contact = Contact::where( 'email', '=', '[email protected]' )->first();

Now the main difference is, using first one with  DB::table( 'contacts' ) will return an object simply to display but second one Contact:: had some extra functionality came out of the box with Laravel Eloquent. Like we can update this contact by using these lines.

$contact->phone_number = '123456789';
$contact->save();

See we can get and update any record in 3 lines. And we can also delete this record by calling delete() Eloquent method on it.

$contact->delete();

This helps in manipulating records. I hope you can start easily with Laravel Eloquent after reading this article. If you have any questions please leave a comment. We appreciate that.