0
votes

In user creation proccess I need to query a external server for additional data and if that happens to fail i need to return an error at validation or creation. How is it best to do this? Here is the default Laravel code for registering user with some of my attemps:

protected function validator(array $data)
{
    $query = queryExternalServerForAdditionalData();

    if($query->success){
      //add data from query to other user data?
      //$data['data'] = $query->data;

      return Validator::make($data, [
          'name' => 'required|string|max:255',
          'email' => 'required|string|email|max:255|unique:users',
          'password' => 'required|string|min:6|confirmed',
      ]);
    } else {
      //somehow return an error, but how?
    }
}

protected function create(array $data)
{
    // or maybe do the query and error return here?
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        // add my additional data
        // 'data' => $data['data']
    ]);
}

So as you can see my question is that how can i return an error from validator or create method? I tried to return redirect() with an error property added, but i got an error that something else was expected by the method calling validator/create and redirect was returned so that doesn't seem to be an option.

1

1 Answers

0
votes

IMHO, the best way to do this is creating form requests.

public function rules()
{
    return [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users|check_server_for_additional_data',
        'password' => 'required|string|min:6|confirmed',
    ];
}

As an example, I added check_server_for_additional_data, a custom validation rule for email field (An error message will appear in the email field).

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('check_server_for_additional_data', function ($attribute, $value, $parameters, $validator) {
            return // queryExternalServerForAdditionalData()
        });
    }
}

Don't forget to defining the error message (resources/lang/LOCALE/validation.php)

"check_server_for_additional_data" => "Umm ohh.. Invalid!",