S
S
Sukhrob Saidov2017-05-05 09:03:26
Laravel
Sukhrob Saidov, 2017-05-05 09:03:26

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();
}

And recently I saw one introductory project where everything is a little different:
PostController
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();
}

True, this is a shortened version, but here's an example:
BlogController
BlogRepository

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D3lphi, 2017-05-05
@1ax3l

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();

You may need to use this piece elsewhere. And yes, this is the way, if your goal is just to insert data, you should not use it. It doesn't make sense. It is better to use the create() or insert() method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question