How to redirect to previous page after successful register in Laravel?

0

Issue

Right now redirectTo is set to /home.

I want to know how I can redirect to the previous page.

I tried using

protected $redirectTo = URL::previous(); 

but I get parse error, expecting ','' or ‘;”

What would be the best solution to approach this problem? I assume I’d need to over-ride the $redirectTo variable somehow with URL::previous() and that would be sufficient.

This is my register controller:

namespace App\Http\Controllers\Auth;

use App\User;
use URL;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{

use RegistersUsers;

/**
 * Where to redirect users after registration.
 *
 * @var string
 */
protected $redirectTo = '/home';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest');
}

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        // 'name' => 'required|max:255',
        'username' => 'required|max:255|unique:users',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return User
 */
protected function create(array $data)
{
    return User::create([
        // 'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
}
}

Solution

The RegisterController uses the RegistersUsers trait. When you submit the form, the register() method of this trait is called. It validates the input, creates and authenticates the user and then redirects to the path specified by the redirectPath() method. This method is actually set in the RedirectsUsers trait, which is used by the RegistersUsers trait.

The redirectPath() method will look for a redirectTo() method on the controller. If it does find this method, it will use whatever is returned from it. If doesn’t find this method, it will redirect to the url specified in the redirectTo property instead.

So, if you need to set the redirect path dynamically, put this in your RegisterController:

protected function redirectTo()
{
    return url()->previous();
}

Read more here.

Answered By – pawelmysior

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More