Skip to content
Advertisement

Laravel 8 Named error bag during registration

Before you mark this question as a duplicate of this question, first understand that this question is based on Laravel 8 while the former is on Laravel 5.4 which handle the auth differently.

I would like to add a named error bag on laravel validation during registration. I am using the default laravel auth

php artisan ui bootstrap --auth

Below is the class that handles registration.

<?php

namespace AppHttpControllersAuth;

use AppHttpControllersController;
use AppProvidersRouteServiceProvider;
use AppModelsUser;
use IlluminateFoundationAuthRegistersUsers;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesValidator;

class RegisterController extends Controller
{
   

    use RegistersUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest');
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }
    
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

Registration is handled by register method in the above class. Laravel has hidden this method and imports it to the above class using the use RegistersUsers; declaration.

enter image description here

To add a named error bag as explained here, I need to access this hidden register method. How do I do it.

I know that one way of doing this is by writing my own register method, but is there an alternative?

I need to add a named error bag because my login and register forms are in the same page.

Advertisement

Answer

You should pass the validator to named error bag, so it can be achieved by overriding register method from RegisterUsers trait:

public function register(Request $request)
{
    $validator = $this->validator($request->all());

    event(new Registered($user = $this->create($request->all())));

    $this->guard()->login($user);

    return redirect('register')->withErrors($validator, 'login');
}

Or you can validate it with an error name bag

public function register(Request $request)
{
    $validator = $this->validator($request->all())->validateWithBag('login');

    event(new Registered($user = $this->create($request->all())));

    $this->guard()->login($user);

    return redirect('register');
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement