簡體   English   中英

Laravel中的自定義請求驗證器

[英]Custom Request Validator in Laravel

我只想使用laravel自定義請求處理程序來驗證API請求。 為此,我創建了一個RegisterRequest,內容如下。

<?php

namespace App\Http\Requests\Api\Auth;

use App\Http\Requests\Request;

class RegisterRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email' => 'required'
        ];
    }
}

而且,我希望它在AuthController中用作:

use App\Http\Requests\Api\Auth\RegisterRequest;

    public function postRegister(RegisterRequest $request)
    {
        dd($request->all());
    }

但是,驗證和請求參數均未顯示在respose中。 所有路由工作正常,但查詢參數為空。 任何幫助將被申請。

版本:Laravel:5.1

我想讓laravel處理所有請求參數,並說出API是成功完成還是出錯。

您的authorize方法應返回true。 如果為false,則由於您無權使用此RegisterRequest類,因此RegisterRequest將返回禁止。 因此,將您的authorize方法從RegisterRequest更改為this:

public function authorize()
{
    return true;
}

編輯 :如果您想以自己的方式回復錯誤消息,可以在RegisterRequest方法中覆蓋如下響應方法:

public function response(array $errors)
{
    return \Response::json($errors);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM