You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 6自定义验证器问题:调用外部API验证游戏账号报错

Hey there! Let's break down what's going wrong here and fix it properly.

First, the error Method Illuminate\View\View::validate does not exist happens because your validator() method is supposed to return a Validator instance, not a view. Laravel's authentication flow expects to call validate() on the return value of this method, but when you return a view instead, it throws that error since views don't have a validate() method.

Instead of trying to handle the API check and return a view directly in the validator method, we should create a custom validation rule that encapsulates the summoner existence check. This is the cleanest, most Laravel-like way to handle custom validation logic, especially when it involves external APIs.

Here's how to do it step by step:

1. Create a Custom Validation Rule

Use Artisan to generate a new rule class (this sets up the boilerplate for you automatically):

php artisan make:rule SummonerExists

2. Implement the Rule Logic

Open the generated file at app/Rules/SummonerExists.php and update it with your API check logic. We'll add some key improvements like URL-encoding the summoner name (to handle spaces/special characters) and using environment variables for your API key (never hardcode secrets!):

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

class SummonerExists implements Rule
{
    /**
     * Check if the summoner name exists via the Riot API
     *
     * @param  string  $attribute The field name being validated
     * @param  mixed  $value The summoner name submitted by the user
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $client = new Client();
        $encodedName = urlencode($value);
        $apiKey = env('APIKEY'); // Pull your key from the .env file

        try {
            $response = $client->request(
                'GET',
                "https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/{$encodedName}?api_key={$apiKey}"
            );

            // Only return true if we get a successful 200 response
            return $response->getStatusCode() === 200;
        } catch (ClientException $e) {
            // 4xx errors (like 404) mean the summoner doesn't exist
            return false;
        }
    }

    /**
     * The error message to show when validation fails
     *
     * @return string
     */
    public function message()
    {
        return 'The summoner name you entered does not exist in the game.';
    }
}

3. Update Your Validator Method

Now, replace your original validator() method in RegisterController.php with this version. We'll remove the manual API check and instead use our new custom rule directly in the validation rules array:

protected function validator(array $data)
{
    return Validator::make($data, [
        'summonername' => ['required', 'string', 'max:255', new \App\Rules\SummonerExists()],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'region' => ['required', 'string'],
        'rank' => ['required', 'string'],
        'lane' => ['required', 'array'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

4. Let Laravel Handle the Rest

Laravel's default registration flow will automatically:

  • Run all validation rules (including our custom summoner check)
  • If validation fails, redirect back to the registration page with your custom error message
  • If validation passes, proceed to create the user account

You don't need to manually return views or handle redirects here—Laravel takes care of that heavy lifting for you!

Bonus Tips

  • Cache API Responses: Riot's APIs have rate limits, so consider caching successful (and failed) checks for a short time (e.g., 5 minutes) to avoid hitting limits.
  • Dynamic Region Support: If your users can select different regions, update the rule to accept the region as a parameter instead of hardcoding euw1.
  • Expand Error Handling: Add catches for other exceptions (like network timeouts) to return a more generic error message for unexpected issues.

That should fix your error and give you a clean, maintainable validation setup!

内容的提问来源于stack exchange,提问作者Umut Savas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:52:52