Search code examples
laravellaravel-5laravel-validationlaravel-requestlaravel-5.7

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


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?


Solution

  • 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) {