B
B
Barney_Gubmle2018-12-17 17:36:43
Laravel
Barney_Gubmle, 2018-12-17 17:36:43

What should be in laravel models?

Good day.
while studying Laravel, I asked myself the question "Am I studying correctly?".
I will be brief.
What should be stored in models?
Poidee in models there has to be a reversal to a DB. But I implemented the database access in the controller as follows:

use App\Modelname;
// у Модели имя аналогичное таблице

class A extends Controller
{
     protected $list;

     public function __construct() 
     {
          $this->list = Modelname::all();
     }
}

And so I thought. Isn't this a "crutch"?
So far, I have climbed into the model only twice.
1 2. Here is such a question. Author (V)(._.)(V) public $timestamps = false;
protected $fillable = ['id', 'name', 'country'];

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
alveryu, 2018-12-17
@alvery

In the constructor, you must have dependencies from the container or
route-model-binding
models loaded from the database. If you need to implement CRUD with pagination, there is a good article on this topic (using the same route model binding for collections): laravel-route-collection- binding

Z
zhulan0v, 2018-12-17
@zhulan0v

The model is ok.
The constructor in the controller is weird. If $this->list is not needed in all controller methods, then it is better to remove it from the constructor, otherwise there will be an extra request to the database.
Usually, dependencies are described in the constructor.

V
Vladislav, 2018-12-17
@vos_50

Well, in models, in fact, a lot of useful things can be specified in addition to $timestamps and $fillable.
For example, relationships (1 to 1, 1 to many, etc.), Scope, mutators, their various methods, etc. Everything is well written about this in the documentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question