Laravel框架登录功能实例

一、添加路由器

Route::group( [ 'middleware'=>[] , 'prefix'=>'admin' , 'namespace'=>'Admin' , 'as'=>'admin.' ] , function(){

    /********************login********************/
    Route::get('login','LoginController@index')->name( 'login' );//登录界面
    /********************登录后的组************************/
    Route::group( [ 'middleware'=>[ 'admin.auth' ] ] , function(){

        Route::get('/','IndexController@index');//后台首页

    });

});

二、制作验证类

<?php

namespace App\Http\Middleware;

use Closure;

class AdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle( $request , Closure $next )
    {
        if( !auth( 'admin' )->check() ){
            return redirect()->route( 'admin.login' );
        }

        return $next( $request );
    }

}

注:放入app\http\middleware文件目录中

三、添加验证类到app\http\kernel.php文件中
头部加上use引入
use App\Http\Middleware\AdminAuth;

在函数中加入

protected $routeMiddleware = [
    'admin.auth'=> AdminAuth::class,
];

四、config\auth.php文件中加上配置

'guards' => [

    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],

],


'providers' => [

    'admins' => [
        'driver' => 'eloquent',
        'model' => \App\Models\Admin::class,
    ]
],

五、建立admin模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{

}

表和模型同名 ,必须有三个字段 username password remember_token

六、login控制器中的登录验证方法


if(auth( 'admin' )->attempt( [ 'username'=>$request->username , 'password'=>$request->password ] , $request->remember ) ){
    return $this->success(  '登录成功' );
}

return $this->fail(  '账号或密码不正确' );

七、返回函数

public function success($info,$data = [])
{
    $return = [
        'data'=>$data,
        'status' => 'y',
    ];
    if($info){
        $return['info'] = $info;
    }
    return response()->json($return);
}

public function fail($info)
{
    $return = [
        'info' => $info,
        'status' => 'n',
    ];
    return response()->json($return);
}

推荐阅读更多精彩内容