[英]Redirect user to specific section/div of page after login/registration
Suppose a user is looking into some section of page and he is not logged in. He than logs in through the link given in the page. 假设用户正在查看页面的某些部分而他没有登录。他通过页面中给出的链接登录。 How can I redirect the user to specific section that he was reading. 如何将用户重定向到他正在阅读的特定部分。
Note: I have already redirected the user to initial page but still can't redirect to the specific section. 注意:我已将用户重定向到初始页面,但仍无法重定向到特定部分。
Use the intended()
method: 使用intended()
方法:
return redirect()->intended();
This method reads the url.intended
value from the session and if it exists, the method redirects a user to this URL. 此方法从会话中读取url.intended
值,如果存在,则该方法将用户重定向到此URL。 If not, by default it redirects a user to /
如果没有,默认情况下会将用户重定向到/
To make it work with a section, use JS to get full URL: 要使其与部分一起使用,请使用JS获取完整的URL:
window.location.href
Then you could make an AJAX call to save current URL to the session manually with: 然后,您可以进行AJAX调用以手动将当前URL保存到会话中:
session(['url.intended' => url()->full()])
Or you could put it into a hidden input and then in a LoginController
get it from a request and save it to the session. 或者您可以将其放入隐藏的输入中,然后在LoginController
从请求中获取它并将其保存到会话中。
The way i did it: 我这样做的方式:
In App\\Http\\Middleware\\Authenticate.php
i update the handle function like this: 在App\\Http\\Middleware\\Authenticate.php
我更新句柄函数,如下所示:
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect('login')->with(['lastUrl' => $request->url()]);
}
}
return $next($request);
}
The important part is return redirect('login')->with(['lastUrl' => $request->url()]);
重要的部分是return redirect('login')->with(['lastUrl' => $request->url()]);
. 。 That way i got the intended url the user tried to access before login so when i login i just redirect the user to the url he tried to access. 这样我就可以在登录前获得用户试图访问的目标网址,因此当我登录时,我只是将用户重定向到他试图访问的网址。
In case the user didn't try to access any page he is just redirected to the default welcome page. 如果用户没有尝试访问任何页面,他只是被重定向到默认的欢迎页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.