Home > Software engineering >  Why laravel 8 form validation request doesn't work as shown in documentation
Why laravel 8 form validation request doesn't work as shown in documentation

Time:11-07

I make custom request by

php artisan make:request UserUpdate

and then fill UserUpdate

public function authorize()
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'name'=>'required|string',
        'email'=>'required|email',
    ];
}

after that call from controller

public function profilepost(UserUpdate $request)
{
    $user = Auth::user();
    $user->name = $request['name'];
    $user->email = $request['email'];
    $user->save();
    return back();
}

when submit form show error

Target class [app\Http\Requests\UserUpdate] does not exist.

Why that happen? Laravel documentation are not correct? Can someone explain me?

CodePudding user response:

solved not use app\Http\Requests\UserUpdate; ,answer is use App\Http\Requests\UserUpdate; . app to App –

CodePudding user response:

I Know it's solved, but this could be useful!

It's good practice to name the file/class like: UpdateUserRequest or UserUpdateRequest.

Why? It's more readable, other programmers understand what it does faster and because of the specific name, class name collitions are avoided.

Remember if you have multiple requests on you project it's allways better to organize them in folders, example:

php artisan make:request User/UserUpdateRequest

This should create a request in User folder, and also with: namespace App\Http\Requests\User

Last but not least a better way to define the rules is:

public function rules()
{
  return [
     'name' => ['required', 'string'],
     'email' => ['required', 'email'],
  ];
}

Why? This gives you the ability to add custom rules to the validations if needed!

  • Related