如果用户未登录 Laravel,则重定向到登录 [英] Redirect to Login if user not logged in Laravel

查看:28
本文介绍了如果用户未登录 Laravel,则重定向到登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 laravel 的新手,

i am new to laravel,

我在控制器的 __construct 中有代码,例如

i have code in my controller's __construct like

if(Auth::check())
{
    return View::make('view_page');
}

return Redirect::route('login')->withInput()->with('errmessage', 'Please Login to access restricted area.');

它工作正常,但我想要的是.将这些编码放在每个控制器中真的很烦人,所以我希望将此验证身份验证并重定向到登录页面在一个地方,可能在 router.phpfilters.php.

its working fine, but what i wants is. its really annoying to put these coding in each and every controller, so i wish to put this Verify Auth and redirect to login page in one place, may be in router.php or filters.php.

我已经阅读了论坛和 stackoverflow 中的一些帖子,并在 filters.php 中添加了代码,如下所示,但这也不起作用.

I have read some posts in forum as well as in stackoverflow, and added code in filters.php like below but that's too not working.

Route::filter('auth', function() {
    if (Auth::guest())
    return Redirect::guest('login');
});

请帮我解决这个问题.

推荐答案

Laravel 5.4

使用内置的 auth 中间件.

Route::group(['middleware' => ['auth']], function() {
    // your routes
});

对于单条路线:

Route::get('profile', function () {
    // Only authenticated users may enter...
})->middleware('auth');

Laravel 文档

这已经内置在 laravel 中了.请参阅 filters.php 中的 auth 过滤器.只需将 before 过滤器添加到您的路线.最好使用一个组并将其包裹在受保护的路线周围:

That's already built in to laravel. See the auth filter in filters.php. Just add the before filter to your routes. Preferably use a group and wrap that around your protected routes:

Route::group(array('before' => 'auth'), function(){
    // your routes

    Route::get('/', 'HomeController@index');
});

或者单条路线:

Route::get('/', array('before' => 'auth', 'uses' => 'HomeController@index'));

要更改重定向 URL 或发送消息,只需根据自己的喜好编辑 filters.php 中的过滤器.

To change the redirect URL or send messages along, simply edit the filter in filters.php to your liking.

这篇关于如果用户未登录 Laravel,则重定向到登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆