使用用户名而不是电子邮件laravel 5.2进行身份验证

时间:2016-08-05 11:07:28

标签: authentication laravel-5.2

以下是我的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') );

});

我正在使用用户名代替Auth的电子邮件ID,但显示的错误

  

SQLSTATE [42S22]:未找到列:1054未知列'电子邮件'   'where子句'(SQL:select * from admin_user其中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,
    ];
}

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

2 个答案:

答案 0 :(得分: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:

doLogout构造函数中添加AuthController's

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

}

答案 1 :(得分:0)

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