Welcome Guest, Not a member yet? Register   Sign In
beforeInsert Validation for unique data
#1

Hi.

I want to verify again before saving the content in the model file.

I want the category name on the form to check if it is in the same sector.

There may be a category with the same name in different sectors. So I can't set is_unique directly.

How can I add the custom error message as well?


PHP Code:
    protected $validationRules = [
        'sector_id' => 'required',
        'category' => 'required'
    ];
    
    
protected $validationMessages = [
        'sector_id' => [
            'required' => 'Select sector',
        ],
        'category' => [
            'required' => 'Select '
        ]
    ];

    protected $beforeInsert = ['checkCategory'];
    
    
protected $beforeUpdate = ['checkCategory'];
    
    
protected function checkCategory(array $data)
    {

        $check_it $this->where('category'$data['data']['category'])
                         ->where('sector_id'$data['data']['sector_id'])
                         ->first();

        if (!empty($check_it)) {

            $fieldName 'category';
            $fieldRules 'is_unique[categories.category]';
            
            $this
->setValidationRule($fieldName$fieldRules);

        }
        
        
return $data;
    
Reply




Theme © iAndrew 2016 - Forum software by © MyBB