3
Good afternoon, use Laravel 5.3 as back-end of a project and I will try to explain in the most succinct way the problem.
Problem: In my project I have the Duplicate model and the Contract.
- A contract creates multiple duplicates by the Contratocontroller
- A duplicate can be created by another controller called Locacaocontroller.
- And finally the duplicate can be created by Duplicatacontroller via store method().
In the database I have the tables:
duplicatas
contratos
They all share basically the same code
$duplicata = new Duplicata()
$duplicata->valor = $request->valor
$duplicata->descricao = $request->descricao
$duplicata->contrato_id = $request->contrato_id
$duplicata->save()
But now I’m going to add our number to the database, and I’m going to have to copy and paste the programming logic into all 3 controllers.
And I found this a bad programming practice and I intend to unify the way duplicates are created, but how do I do that? I’m doing it all wrong?
Create the Duplicates only in Duplicatacontroller, Integrate the dependency where you need to create duplicates and use only the store method of Duplicatacontroller, it makes no sense for the same function in a lot of different places if you can reuse :)
– Felipe Paetzold
But only this method is repeated? If you want, you can create a specific Controller (e.g., Duplicationscontroller) with the methods that will be shared and "extend" it in the 3 controllers you need.
– Pliavi
Or create a class that does this calls in the App Classname and invokes the function. GGWP.
– Diego Souza
The deal is that when a contract is created the system triggers a series of creation of duplicates from the past parameters (maturity, contract value, etc.) via transaction, because in case of an error in the creation of one the entire contract is deleted.
– Cassiano
@Felipepaetzold in the case of the injection of a Controller into another one as I would call the store method? And what to do with the return of it? (Return Response()->json('Duplicate successfully created, 200'))?
– Cassiano
@Cassiano created an answer more or less with a direction for you to follow, there are several ways to do this elegantly, I hope it helps
– Felipe Paetzold