How to Redirect to a Specific Location When Validation Fails in Laravel's Register (User Registration)
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
This article summarizes how to redirect to a specific location when validation fails in Laravel's Register (User Registration).
Laravel 6
Premise
I think this use case is quite rare.
When using Laravel's Auth for registration mechanism, if validation fails
As written in vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php,
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
in this function,
->validate();
is present, so the automatic redirect feature will work.
Conclusion
Therefore, we will override this function.
App/Http/Controllers/Auth/RegisterController.php
public function register(Request $request)
{
$validation = $this->validator($request->all());
if($validation->fails()) {
// Specify the redirect here
return redirect()
// You can change the route part to your preferred location
->route('register')
->withErrors($validation)
->withInput();
}
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
Once you understand where the redirect process is taking place, all you have to do is override (overwrite) the function.
Summary
That's all.
I hope it can be helpful to someone.
For feedback or complaints, please contact me via Twitter DM.
That's all!
Popular Articles
Deploying a PHP 7.4 + Laravel 6 Project to AWS EC2
Implementing Breadcrumbs in Laravel with laravel-breadcrumbs