thomvincent's avatar

Best way to validate

Hello.

I'm saving a simple form of text to a model (App\Brief) successfully to the database. I create a BriefRequest to house all the validation and associated messages. That is working really well.

On that page I also have an instance of Dropzone.js which allows to user to upload multiple images to the server. Each upload creates a polymorphic entry in an "attachments" table. This allows me to easily retrieve all the associated attachments by writing something like $brief->attachments(). It also allows me to add images to other models (App\Designer, App\Pitch, etc).

My question is, how do I check that the App\Brief model has at least 3 images associated with it before it is saved? And how do I tell the user that they have to uploaded 3 images before they can save their form?

I know how to count how many associated images there are for each brief, but how do I validate that number and where?

At the moment I have a simple check in the controller, but I don't think it's the most elegant or reusable solution.

Kind regards, Thom

0 likes
1 reply
thomvincent's avatar
thomvincent
OP
Best Answer
Level 1

I solved this myself by updating the validator instance in my request file like so:

    protected function getValidatorInstance()
    {
        $brief = $this->route()->parameter('briefs');
        $this->merge(array( 'floorPlan' => $brief->floorPlan() ));
        $this->merge(array( 'currentSpace' => $brief->currentSpace() ));
        $this->merge(array( 'currentItems' => $brief->currentItems() ));
        $this->merge(array( 'inspiration' => $brief->inspiration() ));
        $this->merge(array( 'links' => $brief->links ));
        return parent::getValidatorInstance();
    }

Then updating the rules to include the array items added above:

                'floorPlan' => 'required',
                'currentSpace' => 'required',
                'currentItems' => 'required',
                'inspiration' => 'required',
                'links' => 'required',

Please or to participate in this conversation.