Let's assume I have User model that related to models Image, Card, etc. That means when I create a new user, I should create Image and Card instances along with it, e.g. I have something like this in my controller's store method:
DB::beginTransaction();
try {
$user->saveOrFail();
$imageObj = new Image();
$imageObj->user_id = $user->id;
// set the other fields
$imageObj->saveOrFail();
$cardObj = new Card();
$cardObj->user_id = $user->id;
// set the other fields
$cardObj->saveOrFail();
.......................
DB::commit();
}
return redirect('some');
}
For more than 2 related models there is too more code in the controller, so is there any thoughts or recommendations on where to put this code for better scalability?
I would choose Factory. With this pattern you can easily create your new object and along with it anything you need. You juste need to pass the right parameters to your service.
check these docs for creating Factory pattern in SYmfony https://symfony.com/doc/current/service_container/factories.html