How to make the CRUD by model in Laravel?

Asked

Viewed 382 times

0

We can do in the controller the method save() the find($id) the update() and create(). How could I do in that Model had that accountability?

  • The Eloquent already propose this model, if it could better explain its doubt

  • So, in the controller I have an eloquent function called update right? instead of calling update(); no control would be better to pass this method la to the model and call the update method in the controller?

  • no... there must be a reason why duplicating functionality unnecessarily is a conceptual error. Your question seems poorly worded, maybe with an edit it will improve the content.

1 answer

2

Your question is a little vague, but I think I understand your doubt.

How could I make Model take that responsibility?

The model you already have this responsibility. It is the Eloquent who knows how to carry out the search with find, create a new instance with create and update it with save or update (has the delete also right).

Controllers methods are another responsibility. They should orchestrate the various stages of interaction with some CRUD command. They are usually composed of:

  1. Authorisation to carry out the operation
  2. Validation of the application
  3. Execution of the CRUD command
  4. Sending the reply (view, json, etc.)

For each of these steps, Laravel presents several tools:

  1. Authorization: Gates, Policies and Method $this->authorize controller’s
  2. Validation: Validators with Validation Rules and Custom Validation
  3. CRUD: Eloquent model or Querybuilder and DB Facade
  4. Answer: Blade views or automatic JSON formatting

Of course this is a simplified view, but the idea is to make it clear that the role of the Controller is to orchestrate these steps and the role of the Model is just one of them.

  • Fine, but let me ask you, let’s assume. I make a method in the model called store that receives n store parameters($id, $request) , and in the controller I only pass the data coming from the request to the store method in the model Type $store = new Registration(); $store->store($id, $request) where this id comes from the method that is in the controller that passes to the method that is in the model and la in the model I call save(). and return true or false. so distribute the code better and clean the controller. What do you think?

  • @Natanmelo, to make it easier for td world, I’ll ask you to edit the question including this scenario of yours with at least the controller method and model method exemplified. Can it be? Then I expand my answer accordingly. Thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.