用户登录后,laravel重定向到路由

时间:2017-02-12 21:12:26

标签: php laravel laravel-5.3

我是laravel的初学者,我试图重定向到另一条路线如果用户登录,注册和登录工作完美且不是问题,但是当我尝试做的时候

@if(Auth::check())
    {{
        redirect()->route('news')
    }}
@endif

重定向脚本在屏幕上输出如下:

HTTP/1.0 302 Found Cache-Control: no-cache, private Location: http://localhost/red-sec/public/news <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="refresh" content="1;url=http://localhost/red-sec/public/news" /> <title>Redirecting to http://localhost/red-sec/public/news</title> </head> <body> Redirecting to <a href="http://localhost/red-sec/public/news">http://localhost/red-sec/public/news</a>. </body> </html>

请原谅我,如果我犯了菜鸟错误,我对laravel非常新,并且新闻路线设置正确并且正在工作

编辑1: 对于第一条评论,是的,这是我的web.php文件:

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
})->name('home');

Route::post('/signup', [
    'uses' => 'UserController@postSignUp',
    'as' => 'signup'
]);

Route::post('/signin', [
    'uses' => 'UserController@postSignIn',
    'as' => 'signin'
]);

Route::get('/news', [
    'uses' => 'userController@getNews',
    'as' => 'news',
    'middleware' => 'auth'
]);

2 个答案:

答案 0 :(得分:3)

您不应该尝试(并且不能)在视图中重定向。视图应该仅用于显示数据,而不是用于执行业务逻辑。

因为您没有使用控制器来执行任何逻辑(直接从路由器返回视图),您可以执行以下操作:

Route::get('/', function () {
    if(Auth::check()) {
        return redirect()->route('news');
    }

    return view('welcome');
})->name('home');

视图中显示的文本实际上是HTTP响应。

答案 1 :(得分:2)

所以我假设您想知道他们是否已经登录,如果他们想要将他们重定向到登录页面?您可以在Route::get('/signin')上的UserController方法中完成此操作。在返回登录视图之前,您可以执行Auth::check(),如果是,则执行redirect()->route('news')

但是,您应该注意到,Laravel已经提供了大量的身份验证脚手架,which you can read about here.

web.php中,请取代/路线:

Route::get('/', function() {
  if (Auth::check()) {
     return redirect()->route('news');
  }
  else {
    return view('welcome');
  }
}
相关问题