Is it possible to share validation failures between nested controllers?

0

I have two templates, one child of the other, User and Address where User>hasOne>Address and I'm about to do the following:

Request :

[
  'User' => [ 
    'name' => 'fulano', 
    'etc' => 'etc' 
  ],

  'Address' => [ 
    'street' => 'rua x', 
    'etc' => 'etc' 
  ]
]

UserController :

  • Validate the data in% with%
  • Give create no User
  • Calls ['User'] and passing data from AddressController

AddressController :

  • Validate the data in% with%
  • Give create no ['Address']

But I'm not finding a way for case validation to fail in both controllers I can return to the user all the fields that failed.

I've done it once with ['Address'] , but the problem is that if the validation fails in Address it ends there and does not validate the address, not showing if something is wrong, causing the user to have perhaps to correct what he wrote twice, one to correct his data, and another to correct the address because the system did not report that the address was wrong, too.

So what happens to me:

  • Is there any way I can not use try-catch and get all the address errors and move to some place to treat? (I've heard something about UserController or something like this, but I do not know if it's something to use here)

I could validate everything in try-catch , but it would be a gut and in case I needed to make a dispatcher in the Address would need to have the address validation again in UserController ;

How do I get out of this?

Edit: An example of how I was doing (I could not find the original)

// User Controller
public function store($data){
    try {
        $this->validate($data['user']);
        $user = User::create($data);

        // Chama o Store de Address e passa os valores
        $address = (new AddressController())->store($user, $data);

        return $user;
    } catch(ValidationFailException $e) { 
        // Aqui captura a primeira validação que falhar
        Session::flash('fails', $ex->getFails());
        return Redirect::back();
    }
}

// Address Controller
public function store($data){
    try {
        $this->validate($data['address']);
        $address = new Address($data);
        $address->user()->associate($user);
        $address->save();

        return $address;
}

// Ambos os controladores tem um método validador nesse formato
public function validate($data)  {
    $validator = Validator::make($data, [
        'campo' => 'required',
    ]);

    if($validator->fails()){
        throw new ValidationFailException('As seguinter validações falharam', $validator->messages()->toArray());
    }
}
    
asked by anonymous 27.01.2017 / 18:07

0 answers