Should I do data insert for a model inside the controller or inside the model?

Joey Source

As my question title states I would like to know all the best practices and pros/cons of following the "Laravel way" of inserting the data in the db.

Is it a bad practice using the Model::create([...]) for inserting a new row in the database which is related to that controller's model?

Is creating a separate function inside the model itself a much better practice?

If so, why?

phplaraveleloquent

Answers

answered 4 months ago Shoukat Mirza #1

It depends on size of your project you can use your models directly in your controller and use the fluent interface of Eloquent to do your logic.

There is nothing wrong that you call a model in a controller to get data from database.

If there is some complicated query you can create method in your model and than call that method in controller ...

answered 4 months ago MohammadReza #2

In laravel you can use insert in controller , view(blade) or even in route . But recommended is on your controller. This help to make your code clean

answered 4 months ago Tarasovych #3

You can take a look for resource controller. It has already predefined logic like store() method where you can put some Model::create(), as you said.

That's not bad if you also create a method inside model and call it from your controller.

I think, that create() method for straght storing some data from request (from some form on front-end, as an example) is enough. But if you want/need to make more than straight storing model, a separate method inside model might take place. Apart to avoid controller's method overgrowth and keep your code pretty.

The answer really depends on, so maybe you will shed some light on the logic you want to implement.

comments powered by Disqus