Search code examples
laravelfortifylaravel-livewirelaravel-jetstream

How to redirect failed validate on register to an url with anchor in laravel jetstream fortify


If I change validate by validator->fails return redirect..... I get error because login want an instance of $user and I send a response.

This defaults work well but not for me

public function create(array $input)
{
    Validator::make($input, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => $this->passwordRules(),
        'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
    ])->validate();

    return User::create([
        'name' => $input['name'],
        'email' => $input['email'],
        'password' => Hash::make($input['password']),
    ]);
}

Thats give me a:

Illuminate\Auth\SessionGuard::login(): Argument #1 ($user) must be of type Illuminate\Contracts\Auth\Authenticatable, Illuminate\Http\RedirectResponse given, called in ....endor/laravel/fortify/src/Http/Controllers/RegisteredUserController.php on line 57

public function create(array $input)
{
   $validator = Validator::make($input, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => $this->passwordRules(),
        'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
    ]);

    if($validator->fails()) {
        return Redirect::to(URL::previous() . "#my-anchor")->withInput()->with('error', $validator->messages()->first());

    } //Thats I want

    return User::create([
        'name' => $input['name'],
        'email' => $input['email'],
        'password' => Hash::make($input['password']),
    ]);
}

Solution

  • I don't did this before but maybe you can find the way to customize it. The CreateNewUser is called in the RegisteredUserController's store method, and the first return an User's instance. So in this you can

    if($validation->fails())
       return $validation->messages()->first();
    

    and in the store method

    public function store(Request $request, CreatesNewUsers $creator): RegisterResponse
    {
         $user = $creator->create($request->all()));
         if($user instanceof User::class) {
            event(new Registered($user);
            
            $this->guard->login($user);
    
            return app(RegisterResponse::class);
         } else 
         return Redirect::to(URL::previous()."#my-anchor")->withInput()->with('error', $user);
    }
    

    Try this, but I suggest you if works extends this Register controller and just modify this store method