Answer the question
In order to leave comments, you need to log in
Which method is better and why?
Which option is better?
I’m used to working with the model directly in the controller (although I recently read that this is very bad, etc., but I still don’t understand why it’s bad)
Here is a simple example:
PostController
use App\Post;
//...
public function create(Request $request)
{
//validate...
$post = new Post;
$post->slug = $request->slug;
$post->name = $request->name;
$post->story = $request->story;
$post->save();
return redirect()->back();
}
use App\Post;
//...
public function __construct(Post $model)
{
$this->model = $model;
}
public function create(Request $request)
{
$post = new $this->model;
$post->slug = $request->slug;
$post->name = $request->name;
$post->story = $request->story;
$post->save();
return redirect()->back();
}
Answer the question
In order to leave comments, you need to log in
Because the controller, by its very nature, should not work with data, should not contain logic. Its task is to accept the request, possibly check the data for validity, and return the answer. Everything! He can't do anything else. All business logic should be placed in the service layer. And from the controller, you will only call the method of this service and receive a response. In principle, you can write logic in the controller, if the code is short, then, of course, creating a service will be redundant. The repository should work with the data (as in the link you provided)! You don't need to do this in the controller.
It may be more familiar to you, but this is not correct. Controllers grow and become fat. This also implies that you have to duplicate the code.
$post = new Post;
$post->slug = $request->slug;
$post->name = $request->name;
$post->story = $request->story;
$post->save();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question