Why in Laravel out of the box is validation implied in the controller, and not in the model?
The documentation states that the Base App\Http\Controllers\Controller includes a treit ValidatesRequests , which already contains methods for validation.
The question is why does not the base class of the model immediately contain validation methods?
After all, so much has been said about thin controllers of thick models. For example, the answer from @HaruAtari from Toaster:
I think that the “fat model, thin controller” is the most suitable option. All application logic must be contained in models. A model is not just entities from a database, it is also an encapsulated processing logic. And the controller should tell the model what to do and render the views.
For example, this piece of code is wrong:
class MyController { public function myAction() { $user = new User(); $user->load($_POST); if ($user->valiadate()) { $user->saveToDatabase(); } else { throw new Exception("..."); } } } Wrong because the controller knows how the model saves data. That at first there is a validation, and then preservation in. And if you then decide not to carry out a validation, or add another checking method (for example), then you will have to do it everywhere.
Correctly, this is how: in the model, define a method containing logic:
class User { public static function create(array $data) { $record= new static; $record->load($data); if($record->validate()){ $record->saveToDatabase(); } else { throw new Exception("..."); } return $record; } } And in the controller just pull it and transfer data there:
class MyController { public function myAction() { $user = User::create($_POST); } } Thus, all the logic of the model (including validation) is encapsulated inside the class, and other classes do not know how this happens.
This approach makes it easier to maintain the code and also makes writing tests easier.