Models in Laravel

0

Let's see, I have a big question about the models in Laravel. It turns out that in the models one generally stores all the access to data through methods and queries that are made to the BD. Here I do not have that very clear, because I see that access to data through the ORM is much easier. Then I wonder, what do I use them for if from a controller I can do things ??? THANK YOU in advance, but please help me with this doubt to continue taking step with this framework.

    
asked by Reyvi Bilbao Betancourt 06.11.2018 в 19:31
source

1 answer

0

As in any language / framework there are many ways to do things.

  • With Laravel can you make queries directly to the database from your controllers? Yes. Using the Query Builder .
  • Can you do it in another way? of course, by using Eloquent , your ORM, which is an implementation of the Active Record pattern.
  • So which one is better? Well the answer always: depends on the use case.

If you plan to make a small application, with only a few classes / tables, you can use Query Builders. By doing this you would be breaking the MVC pattern as you are logically entering the model into the controller, which really should only map things.

On the other hand, making use of models, allows you to decouple your logic:

  • Your model is the only one in charge of managing the operations of the objects / instances of that class.
  • Centralize maintenance in a single class.

Imagine the following case. You have a table colaboradores in which there is the field con_hijos that returns a boolean indicato true / false . But for business needs, this field should be changed to a type int which should indicate the number of children of the employee.

If you put all the logic in your controllers, you should go to all the controllers methods in which you have used this attribute and modify the logic to know if it is a parent or not (in case you have not created a helper ).

You would go through this:

public function miFuncion()
{
    // colaborador X
    $colaborador = DB::table('colaboradores')->where('id', 1)->first();

    // si cumple la condición actual
    if ($colaborador->con_hijos) // <----------------
    {
        // se ejecuta alguna acción
        $this->notificarBonoPaternidad($colaborador);
    }
    else
    {
        // se ejecuta otra acción
    }
}

to this:

public function miFuncion()
{
    // colaborador X
    $colaborador = DB::table('colaboradores')->where('id', 1)->first();

    // ajustando para que cumpla la condición
    if (count($colaborador->con_hijos)) > 0)  // <----------------
    {
        // se ejecuta alguna acción
        $this->notificarBonoPaternidad($colaborador);
    }
    else
    {
        // se ejecuta otra acción
    }
}

On the other hand, if you deposit this logic in your model, you give it the responsibility of managing these changes because you only want the returned value and add the logic to know the number of children. So the update of this model would be replicated in all parts of your program where you use that function:

app / Collaborator.php

// saber si es padre/madre
public function getConHijosAttribute()
{
    return ($this->con_hijos > 0) ? true : false;
}

// devolver el número de hijos
public function getCantidadHijosAttribute()
{
    return $this->con_hijos;
}

So in your controller you do not need to update anything:

public function miFuncion()
{
    // colaborador X
    $colaborador = Colaborador::find(1);

    // si cumple la condición actuar
    if ($colaborador->con_hijos)
    {
        // se ejecuta alguna acción
        $this->notificarBonoPaternidad($colaborador);
    }
    else
    {
        // se ejecuta otra acción
    }
}

And this is just a case of use, actually the models are very useful because it allows you create attribute s based on others or some logic in particular (as I did above), give it a specific format before returning it to the controllers / views ( casting ). In addition to define your relationships and, with them, limit the scope of these through special conditions. In short, there are many things that allows you to make this beautiful framework.

There are many ways in which you can optimize your code and decouple logic so that it can be maintainable over time. Laravel makes it really easy. I recommend you read the documentation , it's super-explained and not boring at all and also that you see the series Laracasts .

    
answered by 06.11.2018 в 20:15