简体   繁体   English

控制器的laravel 5身份验证

[英]laravel 5 authentication from controller

I was doing authentication in routes.php, which is not a correct way. 我在routes.php中进行身份验证,这不是正确的方法。 Now i am doing authentication in UserController . 现在我在UserController进行身份验证。 I am facing a problem. 我面临一个问题。

In routes.php i was doing this below way. routes.php我正在按照以下方式进行操作。

Route::post('/login',function(){
    $cred = Input::only('username','password');
    if(Auth::attempt($cred)){
        return Redirect::intended('/');
    }else{
        $error = "Username or password is incorrect.";
       return Redirect::to('login', compact('error'));
    }
});

Route::get('/', ['middleware' => 'auth', function(){
    return view('index');
}]);

Now i am using a controller UserController . 现在我正在使用控制器UserController

class UserController extends Controller
{
    public function index()
    {
      Route::post('/login',function(){
        $cred = Input::only('username','password');
        if(Auth::attempt($cred)){
          return Redirect::intended('/');
        }else{
          $error = "Username or password is incorrect.";
        }
     });
    }

And now in routes.php : 现在在routes.php

Route::get('index', ['middleware' => 'auth', 'uses' => 'UserController@index']);

But the following code throws an error : 但是以下代码将引发错误:

MethodNotAllowedHttpException in RouteCollection.php line 201:

how about doing it like this in your route. 在您的路线中如何做到这一点

Route::post('/login', ['uses' => 'UserController@index']);

and in your controller you do the validation. 然后在您的控制器中进行验证。

 public function index()
    {
        $cred = Input::only('username','password');
        if(Auth::attempt($cred)){
          return Redirect::intended('/');
        }else{
          $error = "Username or password is incorrect.";
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM