【问题标题】:Authentication using username instead of email laravel 5.2使用用户名而不是电子邮件 laravel 5.2 进行身份验证
【发布时间】:2016-12-11 18:44:42
【问题描述】:

下面是我的 AuthController 代码

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
//use App\Http\Requests\Request;
use Request;
use View;
use Hash;
use DB;
use Auth;
class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    protected $redirectAfterLogout = '/login';
    protected $username = 'user_name';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
    public function showLogin()
    {
        if (Auth::check()) 
        {
            return redirect('/home');
        }
        else
        {
            return View::make('index');

        }
    }
    public function doLogin()
    {
        //echo 'test';
        $input = Request::all();

        $pass = Hash::make($input['password']);
        //print_r($input);exit;
        //echo $input['username'];exit;
        /*DB::table('admin_user')->insert(
            ['user_name' => $input['username'], 'password' => $pass]
        );*/
        if (Auth::attempt(['user_name' => $input['username'], 'password' => $input['password']])) {
            return redirect('/home');
            //return View::make('home');
        }
        else
        {
            return redirect('/');
        }


    }
    public function doLogout()
    {

        Auth::logout();
        return redirect('/');


    }

}

以下是我的路线代码

Route::get('/',array('uses'=>'Auth\AuthController@showLogin') );
    Route::post('/login',array('uses'=>'Auth\AuthController@doLogin'));


//Route::get('/login',array('uses'=>'Login@showLogin') );

Route::group(['middleware' => ['web', 'auth.basic']], function(){


    Route::get('/home',['uses'=>'Home@getHome']);
    Route::get('/logout',array('uses'=>'Auth\AuthController@doLogout') );

});

我使用用户名而不是电子邮件 ID 进行身份验证,但显示以下错误

SQLSTATE[42S22]:未找到列:1054 未知列“电子邮件”在 'where 子句' (SQL: select * from admin_user where email = admin 限制 1)

下面是我的 kernal.php 代码

    <?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

请帮助我如何使用用户名登录。 提前致谢。

【问题讨论】:

  • 登录或注册错误?
  • 在路由首页提交表单后登录
  • 我在您的代码中找不到任何问题 :-(
  • 你能给我看看你的内核文件吗?只有 routemidllewareproviders
  • 你说的是auth.php文件?

标签: authentication laravel-5.2


【解决方案1】:

更新:

auth中间件添加到特定路由

Route::group(['middleware' => ['web']], function(){
        Route::get('/',array('uses'=>'Auth\AuthController@showLogin') );
        Route::post('/login',array('uses'=>'Auth\AuthController@doLogin'));
        Route::get('/home',['uses'=>'Home@getHome'])->middleware('auth');//update
        Route::get('/logout',array('uses'=>'Auth\AuthController@doLogout') );
    });

要在登录后重定向到预期页面,请将您的 doLogin() 函数替换为以下内容:

public function doLogin()
    {

        $input = Request::all();

        $pass = Hash::make($input['password']);

        if (Auth::attempt(['user_name' => $input['username'], 'password' => $input['password']])) {
            return redirect()->intended('/home');//This line is changed
        }
        else
        {
            return redirect('/');
        }
    }

说明: intended() 方法将用户重定向到上一个页面,用户从那里重定向到登录页面。它需要一个默认路由作为参数,如果用户直接来到这里,他将被发送到这里。

更新 2:

AuthController's 构造函数中添加doLogout

public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'doLogout']);

}

【讨论】:

  • 我用过有意();但是提交后我的页面一直在登录页面上
  • Route::group(['middleware' =&gt; ['web']], function(){ Route::get('/',array('uses'=&gt;'Auth\AuthController@showLogin') ); Route::post('/do_login',array('uses'=&gt;'Auth\AuthController@doLogin'));//update Route::get('/login',array('uses'=&gt;'Auth\AuthController@showLogin')); Route::get('/logout',array('uses'=&gt;'Auth\AuthController@doLogout') ); }); Route::get('/home',['uses'=&gt;'Home@getHome'])-&gt;middleware('auth'); 我已将登录表单发布 url 设置为 do_login 但登录后它重定向到登录 url
  • 你检查过我发送的控制器吗?
  • 另外,您认为您有显示验证错误的代码吗?
  • 是的,我已经检查过了。但我认为问题是因为身份验证中间件。当我使用身份验证中间件时,我无法转到主页,它会将我重定向回登录页面
【解决方案2】:

您可以通过编写 protected $username = 'username' 来简单地覆盖 AuthController 中的 $username

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2015-03-13
    • 2021-03-08
    • 1970-01-01
    相关资源
    最近更新 更多