Welcome Guest, Not a member yet? Register   Sign In
How to run Transactions in controller?

(This post was last modified: 04-03-2021, 05:20 AM by yahyaerturan. Edit Reason: Use coding block this time. )

(04-02-2021, 06:01 AM)InsiteFX Wrote: Transactions should be handled in the Model that's where your business logic should be.

Initializing the database and accessing it in the controller is breaking the mvc logic.

Make methods in your model for this then call that method from the controller.

I am not sure if it is the best practice but if not I want to learn the correct way Smile

I think it should be handled in controller for the following reasons:

- In a controller endpoint it can be used methods from different models which we want all to be in same transaction. For example, adding new tags to article when adding a new article, or adding new product tags when adding a new product.
- Sending response from API endpoint if transaction fails.

Here is an example how I use it:

PHP Code:
* @method POST
* @url /api/{version}/company
public function create(): ResponseInterface
    $createData $this->request->getJSON();


    $tagIds $this->handleIndustries($createData); // Adding new industries

    $isSaved $this->model->save($createData);

    if (false === $isSaved) {
        return $this->failValidation($this->model->errors(), Domain::COMPANY);

    $insertID $this->model->getInsertID();

    if (false === $qB->addOrUpdateRelations($tagIds$insertID)) {
        return $this->failPersistence(
            'One or more relation(s) could not be saved.',


    if (false === $this->db->transStatus()) {
        return $this->failPersistence(
            'An error occurred in transaction.',

    $data $this->model->find($insertID);

    return $this->respondCreated($data);

If there is a better way, I'd like to learn..

Messages In This Thread
RE: How to run Transactions in controller? - by yahyaerturan - 04-02-2021, 10:08 PM

Theme © iAndrew 2016 - Forum software by © MyBB