Answer the question
In order to leave comments, you need to log in
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();
}
}
public $timestamps = false;
protected $fillable = ['id', 'name', 'country'];
Answer the question
In order to leave comments, you need to log in
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
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.
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 questionAsk a Question
731 491 924 answers to any question