M
M
Muhammad2015-06-14 09:52:42
Validation
Muhammad, 2015-06-14 09:52:42

Complex validation in Laravel?

There is a Product model with three methods add($data), edit($id, $data) and validate($data).
Validation occurs at the very beginning of the add and edit methods:

public static function add($data)
{
  Product::validate($data);
  ...
}

public static function add($id, $data)
{
  Product::validate($data);
  ...
}

The validate method has the following rule:
$rules = array(
  ...
  'url'  => 'required|min:5|max:512|unique:products',
  ...
);

The problem is that if you leave the url the same when editing, the validator gives an error that the URL is already taken. Tell me, please, how can I solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Kuznetsov, 2015-06-14
@muhammad_97

$rules = array(
    'url' => 'required|unique:products,url,{{$id}}',
);

public function validate($data, $id = null)
    {
        $rules = $this->rules;
        foreach($rules as $keys => $value) {
            $validations = explode('|', $value);
            foreach($validations as $key => $value) {
                $validations[$key] = str_replace('{{$id}}', $id, $value);
            }
            $implode = implode("|", $validations);
            $rules[$keys] = $implode;
        }
        
        return \Validator::make($data, $rules);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question