Laravel 5.7 - 覆盖请求验证类中的 all() 方法以验证路由参数?

Ali*_*ari 4 laravel laravel-5 laravel-validation laravel-request laravel-5.7

我想验证请求验证类中的路由参数。我知道这个问题之前已经被问过很多次了,但是根据这个问题,我覆盖了all()方法并收到了这个错误:

Class App\Http\Requests\DestroyUserRequest does not exist
Run Code Online (Sandbox Code Playgroud)

我正在使用 Laravel 5.7。

路线:

Route::delete('/user/{userId}/delete', 'UserController@destroy')->name('user.destroy');
Run Code Online (Sandbox Code Playgroud)

控制器:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\DestroyUserRequest;
use App\User;

class UserController extends Controller
{

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy(DestroyUserRequest $request)
    {
        User::find($request->route('userId'))->delete();
        return $request->route('userId');
    }
}
Run Code Online (Sandbox Code Playgroud)

销毁用户请求:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'userId' => 'integer|exists:users,id'
        ];
    }

    public function all()
    {
        $data = parent::all();
        $data['userId'] =  $this->route('userId');
        return $data;
    }
}
Run Code Online (Sandbox Code Playgroud)

覆盖 all() 方法有什么问题?

Mar*_*łek 5

你得到的错误似乎很奇怪。我相信问题出在这里,因为您的方法签名与父方法不同。

它应该是:

public function all($keys = null)
{
    $data = parent::all($keys);
    $data['userId'] =  $this->route('userId');
    return $data;
}
Run Code Online (Sandbox Code Playgroud)

因为签名Illuminate/Http/Concerns/InteractsWithInput.php是:

/**
 * Get all of the input and files for the request.
 *
 * @param  array|mixed  $keys
 * @return array
 */
public function all($keys = null)
Run Code Online (Sandbox Code Playgroud)

更改是在 Laravel 5.5 中进行的。您可以阅读升级指南

全部方法

如果你覆盖了 Illuminate\Http\Request 类的 all 方法,你应该更新你的方法签名以反映新的 $keys 参数:

公共函数所有($keys = null){