Welcome Guest, Not a member yet? Register   Sign In
Struggling with transaction using multiple models
#6

(This post was last modified: 10-11-2020, 04:15 PM by mlurie.)

(10-09-2020, 10:07 PM)InsiteFX Wrote: Ok, let me know how you make out on this.

I like to perform most of my validation at the model level.  It saves a lot of duplicate code and in my opinion better protects the data going into the database.

Once I realized that the validation was failing before the database query executed, I had to figure out a way to validate the data for two different models before beginning the database transaction.  I also wanted to leave my rules in the model for the reasons I stating above.  I ended up merging the two validationRules arrays for each model and then perform validation at the controller level.  After the POST data passes validation in the controller, the database transaction executes.  This does mean that the data is validated multiple times, once in the controller and then once again by each model, but there is basically no code duplication and I don't think it requires that much extra overhead.  Hopefully this will help someone else struggling with the same quandary:

PHP Code:
if($this->request->getMethod() == 'post') {
    $property = $this->request->getPost(); //Save array of POST data

    //Instantiate database model
    $property_model = new PropertyModel;
    $unit_model = new UnitModel;

    //Merge model validation rules for controller level validation
    $ctrlr_validation_rules = array_merge($property_model->validationRules, $unit_model->validationRules);

    //Perform validation at the controller level before starting transaction
    if($this->validate($ctrlr_validation_rules)) {
        $this->db->transStart(); //Begin Transaction

        $property_model->insert($property);
        $property['property_id'] = $property_model->getInsertUniqID();
        $unit_model->insert($property);

        $this->db->transComplete(); //End Transaction

        if($this->db->transStatus() === TRUE) {
            $data['property']->fill($property);
            session()->setFlashdata('success', $data['property']->property_name . ' added successfully!');
            return redirect()->to('/properties/' . $property_model->getInsertUniqID());
        }
    }
    $data['errors'] = $this->validator->getErrors();

Reply


Messages In This Thread
RE: Struggling with transaction using multiple models - by mlurie - 10-10-2020, 08:59 PM



Theme © iAndrew 2016 - Forum software by © MyBB