Home > Net >  Laravel controller validation Request does not exist
Laravel controller validation Request does not exist

Time:11-15

I'm using Laravel 8 validation, and what i'm trying to do is to validate a form with some input name, unique to table Sizes column "name" where it also depends on another column speciesId that the value from $request->speciesId.

The function in Controller is looks like this

    public function storeSize(Request $request)
    {
        $validated = $request->validate(
            [
                'name' => [
                    'required', Rule::unique('sizes')->where(function ($query) {
                        return $query->where('speciesId', $request->speciesId);
                    })
                ],
                'speciesId' => 'required'
            ]
        );
    }

already add use Illuminate\Http\Request; and use Illuminate\Validation\Rule; but still got "ErrorException Undefined variable: request".

when i'm try to var_dump($request) or echo $request->speciesID, the variable and value is present.

my question is, why the validation function doesn't recognize the Request variable?

CodePudding user response:

The error occurs because inside your function call $request is not available. You need to make it available by adding use $request to function ($query):

$validated = $request->validate([
  'name' => [
    'required', Rule::unique('sizes')->where(function ($query) use ($request) {
       return $query->where('speciesId', $request->speciesId);
     })
  ],
  'speciesId' => 'required'
]);
  • Related