LoginController和RegisterController的JSON错误应该是字符串而不是数组

时间:2018-01-10 07:53:04

标签: laravel laravel-5.5

我使用的是Laravel 5.5.14(php artisan --version)。我正在使用Laravel创建一个REST API。

当我收到错误时,它的形状如下所示:

[
    'message' => 'The given data was invalid.',
    'errors' => [
        'email' => ['The email field is required.'],
        'password' => ['The password field is required.']
    ]
]

我的

我们在errors数组中看到,每个字段(emailpassword)而不是字符串,是一个单个字符串的数组。可能会有多个错误,这就是为什么它是一个数组?即使有一个以上的错误,我想告诉Laravel只报告没有数组的第一个错误,这可能吗?

在我的api.php我有这个:

Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout');
Route::post('register', 'Auth\RegisterController@register');

我的LoginController.php看起来像这样:

public function __construct()
{
    $this->middleware('guest')->except('logout');
}

public function login(Request $request)
{
    $this->validateLogin($request);

    if ($this->attemptLogin($request)) {
        $user = $this->guard()->user()->load('pets');
        $user->generateToken();

        return $user;
    }

    return $this->sendFailedLoginResponse($request);
}

public function logout(Request $request)
{
    $user = Auth::guard('api')->user();

    if ($user) {
        $user->api_token = null;
        $user->save();
    }

    return ['ok' => true];
}

我的RegisterController.php看起来像这样:

public function __construct()
{
    $this->middleware('guest');
}

/**
 * The user has been registered.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function registered(Request $request, $user)
{
    $user->generateToken();

    return response()->json($user, 201);
}

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6|confirmed',
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */
protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
}

2 个答案:

答案 0 :(得分:1)

来自the docs

  

$errors变量将是Illuminate\Support\MessageBag

的实例

显示错误from the docs

的示例
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

答案 1 :(得分:1)

validateLogin覆盖到以下内容,或者您​​可以给它一个different名称并通过controller函数调用它 -

public function validateLogin($request){
  $rules = [
        'user_name' => 'required|string',
        'password' => 'required|string',
    ];
    $validator = Validator::make($request->all(), $rules);

    if ($validator->fails()) {
        $errorResponse = $this->validationErrorsToString($validator->errors());
        return response()->json(['message' => 'The given data was invalid.', 'errors' => $errorResponse],400);
    }
}

使用此方法制作另一个函数transform您对预期格式的回复 -

private function validationErrorsToString($errArray) {
    $valArr = array();
    foreach ($errArray->toArray() as $key => $value) {
        $valArr[$key] = $value[0];
    }
    return $valArr;
}

不要忘记在控制器文件的start添加此内容 -

use Validator;

希望这可以帮助你:)