Laravel 5.7 - Override all() method in Request validation Class to validate route parameters?

◇◆丶佛笑我妖孽 提交于 2019-12-07 13:35:11

问题


I want to validate the route parameters in the Request validation class. I know this question has been asked many times before but According to this question I override all() method and I receive this error:

Class App\Http\Requests\DestroyUserRequest does not exist

I'm using Laravel 5.7.

Route:

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

DestroyUserRequest:

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

What is wrong to override all() method?


回答1:


The error your get seems to be quite strange. I believe the problem is here because your method signature is not the same as parent.

It should be:

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

because signature of Illuminate/Http/Concerns/InteractsWithInput.php is:

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

The change was made in Laravel 5.5. You can read in 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) {



来源:https://stackoverflow.com/questions/52402139/laravel-5-7-override-all-method-in-request-validation-class-to-validate-rout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!