Laravel 5.7 - 重写请求验证类中的 all() 方法来验证路由参数?

标签 laravel laravel-5 laravel-validation laravel-request laravel-5.7

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

Class App\Http\Requests\DestroyUserRequest does not exist

我使用的是 Laravel 5.7。

路线:

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

Controller :

<?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');
    }
}

销毁用户请求:

<?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;
    }
}

重写 all() 方法有什么问题?

最佳答案

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

应该是:

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

因为 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)

此更改是在 Laravel 5.5 中进行的。您可以阅读upgrade guide :

The all Method

If you are overriding the all method of the Illuminate\Http\Request class, you should update your method signature to reflect the new $keys argument:

public function all($keys = null) {

关于Laravel 5.7 - 重写请求验证类中的 all() 方法来验证路由参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52402139/

相关文章:

php - 如何在View上使用Youtube类

laravel - 使用 Laravel Eloquent 获取所有最新记录

Laravel - 如何添加新连接到database.php

Laravel Blade : concatenating variables as string inside old() function

php - laravel 验证语法错误

laravel - 我如何在 Laravel 5.5 的 FormRequest 类中返回自定义响应?

php - Eloquent 限制关系字段

php - 拉维尔 5 : View Composer and Service Provider not working

php - Laravel 在特征启动期间设置/修改模型属性

php - 如何从 Laravel 应用程序中的 Controller 方法手动将带有特定消息的错误页面返回到 $errors 中?