在使用网站之前过滤登录-Laravel Framework


Filters login before using website - Laravel Framework

与标题相同,我想让所有人在使用我的trang web时,必须登录(看起来像FB或Twitter,…),并要求如下:

  • 如果当前URL是"/"(主页),则系统会显示已注册的接口。(显示而不是重定向)

  • 如果诸如其他URL"/"(主页),则系统重定向到登录页面。

有人能帮我吗?我使用的是laravel框架。

Laravel使用称为filter的强大功能。

您可以在任何需要的Route::操作中使用它们。

但一个小小的例子可能会对你有所帮助。

按照您的要求:

// Check manualy if user is logged. If so, redirect to the dashboard.
// If not, redirect to the login page
Route::get('/', function()
{
   if (Auth::check()) // If user is logged
       return View::make('dashboard')
   return View::make('/login');
}
// Each routes inside this Route::group will check if the user is logged
// Here, /example will only be accessible if you are logged
Route::group(array('before'=>'auth', function()
{
   // All your routes will be here
   Route::get('/example', function()
   {
     return View::make('contents.example');
   }
});

当然,过滤器auth是在Laravel中构建的。您可以在app/filters.php中找到此文件并根据您的需要进行修改。如下:

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