在Laravel中成功注册后,如何重定向到上一页? [英] How to redirect to previous page after successful register in Laravel?
问题描述
现在将redirectTo设置为/home.
Right now redirectTo is set to /home.
我想知道如何重定向到上一页.
I want to know how I can redirect to the previous page.
我尝试使用
protected $redirectTo = URL::previous();
但是我得到解析错误,期望是','' or
';''
but I get parse error, expecting ','' or
';''
解决此问题的最佳解决方案是什么?我认为我需要以某种方式使用URL :: previous()覆盖$ redirectTo变量,这样就足够了.
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.
这是我的注册控制器:
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']),
]);
}
}
推荐答案
RegisterController
使用RegistersUsers
特性.提交表单时,将调用此特征的register()
方法.它验证输入,创建并验证用户,然后重定向到redirectPath()
方法指定的路径.实际上,此方法是在RedirectsUsers
特征中设置的,而RegistersUsers
特征则使用该方法.
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.
redirectPath()
方法将在控制器上查找redirectTo()
方法.如果找不到,则将重定向到redirectTo
属性中指定的url.如果找不到此方法,它将使用从它返回的任何内容代替.
The redirectPath()
method will look for a redirectTo()
method on the controller. If doesn't find one, if will redirect to the url specified in the redirectTo
property. If it doesn't find this method, it will use whatever is returned from it instead.
因此,如果您需要动态设置重定向路径,请将其放置在RegisterController中:
So, if you need to set the redirect path dynamically, put this in your RegisterController:
protected function redirectTo()
{
return url()->previous();
}
在此处了解更多信息.
这篇关于在Laravel中成功注册后,如何重定向到上一页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!