Best & useful Concepts of laravel Eloquent

The Eloquent Model can actually do tons of things in a very smart and easy way. However, something can be improved in terms of code to write every time you want to do a specific operation.

Usually, when creating a new model instance, you are probably using some data that the user previously typed in to a form.

Adding a new author to our database can be the perfect example. All you have to do is to insert the first and last names in to a form and then press save.

Then, in the dedicated post route (or relative controller method), you will do something similar to the following:

<?php


public function postAdd(Request $request)
{
  $author = new Author;

  $author->first_name = $request->input('first_name');
  $author->last_name = $request->input('last_name');

  $author->save();
}

That’s quite fine. However, you will probably also have to validate the user input.

So, assuming that you are still in a controller, you could add a controller validator call, just like this one:

<?php


public function postAdd(Request $request)
{
  $this->validate($request, [
    'first_name' => 'required',
    'last_name' => 'required'
  ], [
    'first_name.required' => 'You forgot the first name!',
    'last_name.required' => 'You forgot the last name!'
  ]);

  $author = new Author;

  $author->first_name = $request->input('first_name');
  $author->last_name = $request->input('last_name');

  $author->save();
}

Once again, saved the day!

 

Single Responsibility Principle

Now, very often, developers debate the responsibilities of a single class in terms of what that class has to do and what not. Everyone has a thought about the topic.

The Single Responsibility Principle, a part of the SOLID principles, is very clear about that—put simply, the principle says that a class should do one and only one thing.

On the other hand, however, you will often find very big classes. The Eloquent Model is one of them. At the time of writing, the IlluminateDatabaseEloquentModel counts 3,399 lines of code. Not exactly something small!

Obviously, the Model doesn’t perform a single operation; it fills its own attributes, deals with relationships, and serializes its own attributes. Yes, it goes far beyond the principle you just read.

So, what’s the deal with it?

Well, even if it is very big, a Model like this allows you to perform many operations using a single class.

A perfect example is how you can use a Model as a model, like this:

<?php

$user = new User;

// using magic methods...
$user->first_name = 'Francesco';
$user->last_name = 'Malatesta';

...

You can also use it as a factory (a class that is used to create instances in a more elegant and better way) using the create() method:

<?php

$user = User::create([
  'first_name' => 'Francesco',
  'last_name' => 'Malatesta',
]);

If this isn’t enough, the Model also handles everything related to the persistence of the instance:

<?php

$user = new User;

// some assignments...
$user->first_name = 'Francesco';
// ...

// and then save!
$user->save();

All using a single class—that’s the main advantage.

You are probably asking yourself what he is trying to say with all this stuff. The answer is really simple: there isn’t always a single correct solution. Some people hate the Eloquent Model, some people love it.

So, in this specific situation, I will add new features to the existing Model class creating a new Eloquent Model… the Aweloquent!

Note

Before we go any further, here’s a clarification. I will repeat it again, but I also want to say it now. In the following part of this chapter, we will extend the Model class adding a feature that, in Laravel, is handled by the Validator class. I am not teaching you this because I want you to do this, but because I want to show you how to extend the Model class.

For instance, you will probably find thesmart password hashing feature stupid, but it’s just an example. Extending Models and using repositories are two different techniques, which are totally separated. I am just giving you the knowledge, then you can choose what to do, and I am sure you will do the right thing, hero!

 

Auto Hydrate

Instead of assigning attributes individually, or passing them in an array, the Aweloquent Model will be able to read the current request and autopopulate its attributes without any other code lines.

This means that you will be able to use the following:

<?php

$user = new User;
$user->save();

Instead of the more classic:

<?php

$user = new User;

$user->first_name = 'Francesco';
$user->last_name = 'Malatesta';
// other assignments here...

$user->save();




Model self-validation

You will be able to specify validation rules and messages as static properties of a Model. Then, the Model will automatically perform the validation operation you need, without using any external classes or controller validators. You will be able, also, to assign a certain rule to a certain operation (the 'create' or the 'update' operation, or both).

So, in your Model, you will have something like this:

<?php namespace App;

use AppAweloquentAweloquentModel;

class Author extends AweloquentModel {

  protected $fillable = [
    'first_name', 'last_name', 'bio'
  ];

  protected static $rules = [
    'everytime' => [
      'first_name' => 'required'
    ],

     'create' => [
      'last_name' => 'required'
    ],

    'update' => [
      'bio' => 'required'
    ],
  ];

  protected static $messages = [
    'first_name.required' => 'You forgot the first name!',
    'last_name.required' => 'You forgot the last name!',
    'bio.required' => 'You forgot the biography!'
  ];

}







we’ll add more concepts . check back for more ..

About the author

Deven Rathore

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

  • Tiago Oliveira Farias

    Great article

    • Deven Rathore

      thanks

  • Jonathan Duran

    Nice!!!

    • Deven Rathore

      thanks

  • Mu.Ah

    i never knew about the model self validation part, many thanx for that

    for the *Auto Hydrate* i believe it would be `Model::create($request->all())` or `Model::find($id)->update($request->all())` or am i missing something ?

Pin It on Pinterest

Shares