我在Laravel中创建了一个登录/注册页面,它运行正常,但我想通过允许经过身份验证的用户访问该网址来保护路由。
这是我的web.php:
Route::get('/', [
'uses' => 'UserController@getLogin',
'as' => 'login'
]);
Route::get('/signup', [
'uses' => 'UserController@getSignup',
'as' => 'signup'
]);
Route::get('/logout', [
'uses' => 'UserController@getLogout',
'as' => 'logout'
]);
Route::group(['prefix' => 'app'], function(){
Route::post('/newuser', [
'uses' => 'UserController@postSubmitSignup',
'as' => 'submitsignup'
]);
Route::post('/submitsignup', [
'uses' => 'UserController@postSubmitLogin',
'as' => 'submitlogin'
]);
Route::get('/home', [
'uses' => 'UserController@getDashboard',
'as' => 'dashboard'
])->middleware('auth');
// I also tried 'middleware' => 'auth', ends in same thing
});
在我的UserController.php中:
public function getSignup(){
$organizations = Organizations::all()->where('deleted', '0')->all();
return view('pages.signup', ['organizations' => $organizations]);
}
public function getLogin(){
return view('pages.login');
}
public function getDashboard(){
return view('pages.dashboard');
}
public function getLogout(){
Auth::logout();
return redirect()->route('login');
}
public function postSubmitSignup(Request $request){
$newuser = new User();
$newuser->firstname = $request['firstname'];
$newuser->lastname = $request['lastname'];
$newuser->username = $request['username'];
$newuser->email = $request['email'];
$newuser->password = bcrypt($request['password']);
$newuser->passwordhint = $request['passwordhint'];
$newuser->organization = $request['organization'];
$newuser->location = $request['location'];
$newuser->phone = $request['phone'];
$newuser->signupnote = $request['remarks'];
$newuser->save();
return redirect()->route('login');
}
public function postSubmitLogin(Request $request){
if(Auth::attempt(["username" => $request['username'], "password" => $request['password']])){
return redirect()->route('dashboard');
}
session()->flash('invalid', 'Bad Credentials');
return redirect()->back()->withInput();
}
当我尝试使用有效凭据登录时,收到以下错误消息,网址似乎为http://website.com/login
,但登录页面位于http://website.com/
:
Sorry, the page you are looking for could not be found.
1/1 NotFoundHttpException in RouteCollection.php line 161:
in RouteCollection.php line 161
at RouteCollection->match(object(Request)) in Router.php line 780
at Router->findRoute(object(Request)) in Router.php line 610
at Router->dispatchToRoute(object(Request)) in Router.php line 596
at Router->dispatch(object(Request)) in Kernel.php line 267
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) in Pipeline.php line 53
当我尝试直接访问仪表板网址时,出现同样的错误。我应该如何正确地做到这一点,如果有人能解释为什么会这样,那就太好了。
答案 0 :(得分:1)
您需要对路线进行分组,如下所示
Route::group(['middleware' => 'auth'], function(){
Route::get('/logout', [
'uses' => 'UserController@getLogout',
'as' => 'logout'
]);
// and your other routes which you wanna protect
}
现在,您将在其中添加的注销路线和其他路线只能由经过身份验证的用户访问,简单来说就是登录的用户。