laravel Auth的使用

1.安装扩展,laravel的 php artisan make:auth 命令已不能用,需要用以下命令替代:

composer require laravel/ui
php artisan ui:auth

执行完成后会在web.php中自动添加路由:

Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

其中 Auth::routes() 加载自动生成的路由配置,具体文件为:vendor\laravel\ui\src\AuthRouteMethods.php

 

2.生成数据表:

php artisan migrate

注意,如果在执行时报错,可能是由于数据库版本造成,需要进行以下修改:
app\Providers\AppServiceProvider.php 文件中 boot 方法增加代码:Schema::defaultStringLength(191);

此时,可以访问home来访问生成的应用程序。

 

 

如果我们想用自己的数据表,只用auth进行验证,操作如下:
1.创建数据表:

CREATE TABLE `member` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL DEFAULT '',
  `password` varchar(255) NOT NULL DEFAULT '',
  `age` tinyint(3) NOT NULL DEFAULT '0',
  `sex` tinyint(3) NOT NULL DEFAULT '0',
  `created_at` int(11) NOT NULL DEFAULT '0',
  `updated_at` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

注意:laravel自带的Auth登录功能,密码使用的是hash加密 $crypt = password_hash($password, PASSWORD_DEFAULT),在添加测试数据时请注意密码加密方式。

 

2.创建model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Member extends Authenticatable
{
    use HasFactory;

    protected $table = 'member';

    //性别配置
    const SEX_UN    = 0;
    const SEX_BOY   = 1;
    const SEX_GIRL  = 2;
    public static $sexText = [
        self::SEX_UN    => '未知',
        self::SEX_BOY   => '男',
        self::SEX_GIRL  => '女',
    ];

    //自动维护时间戳
    public $timestamps = true;

    //指定时间为unix时间戳
    public function getDateFormat() {
        return time();
    }

    //查询出的时间戳不做任何处理
    public function asDateTime($value)
    {
        return $value;
    }

    //避免转换时间戳为字符串
    public function fromDateTime($value)
    {
        return empty($value)?$value:$this->getDateFormat();
    }

}

 

3.创建控制器:

<?php

namespace App\Http\Controllers;

use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MemberController extends Controller
{

    //登录页面
    public function login() {
        return view('member.login');
    }

    //登录逻辑
    public function loginlogic(Request $request) {
        $credentials = $request->only('username', 'password');
        $result = Auth::guard('member')->attempt($credentials);
        if($result) {
            return redirect('member/home')->with('success_msg','登录成功');
        }
        return redirect()->back()->with('error_msg', '账号或密码错误');
    }

    //登录成功页面
    public function home() {
        //获取当前登录信息
        $info = Auth::guard('member')->user();
        //性别配置信息
        $sexText = Member::$sexText;
        return view('member.home', [
            'info'      => $info,
            'sexText'   => $sexText,
        ]);
    }

    //退出登录逻辑
    public function logout() {
        Auth::logout();
        return redirect('member/login');
    }

}

 

4.在view/member目录下创建视图文件:
创建login.blade.php:

<form method="post" action="{{url('member/loginlogic')}}">
    @csrf
    <table>
        <tr>
            <td>账号</td>
            <td>
                <input type="text" name="username">
            </td>
        </tr>
        <tr>
            <td>密码</td>
            <td>
                <input type="password" name="password">
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="登录">
            </td>
        </tr>
        <tr style="{{Session::has('error_msg') ? '' : 'display: none;'}}">
            <td colspan="2" style="font-size: 12px;color: red;">
                错误提示信息:{{Session::has('error_msg') ? Session::get('error_msg') : ''}}
            </td>
        </tr>
    </table>
</form>

创建home.blade.php:

<table>
    <tr>
        <td>当前页:home</td>
        <td><a href="{{url('member/logout')}}">退出登录</a></td>
    </tr>

    <tr>
        <td colspan="2"></td>
    </tr>

    <tr>
        <td>用户名:</td>
        <td>{{$info->username}}</td>
    </tr>
    <tr>
        <td>性别:</td>
        <td>{{$sexText[$info->sex]}}</td>
    </tr>
    <tr>
        <td>年龄:</td>
        <td>{{$info->age}}</td>
    </tr>
    <tr>
        <td>注册时间:</td>
        <td>{{date('Y-m-d H:i', $info->created_at)}}</td>
    </tr>
</table>

 

5.修改config\auth.php配置

//guards下增加
        'member' => [
            'driver' => 'session',
            'provider' => 'member',
        ],

//providers下增加
        'member' => [
            'driver' => 'eloquent',
            'model' => App\Models\Member::class,
        ],

 

6.创建中间件:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class memberActivity
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if(!Auth::guard('member')->check()) {
            return redirect('member/login');
        }
        return $next($request);
    }
}

 

7.Kernel.php中$routeMiddleware下添加路由中间件:

'member' => \App\Http\Middleware\memberActivity::class,

 

8.设置路由:

Route::group(['prefix'=>'member', 'middleware'=>['web']], function() {
    Route::get('/login', [\App\Http\Controllers\MemberController::class, 'login']);
    Route::post('/loginlogic', [\App\Http\Controllers\MemberController::class, 'loginlogic']);

    Route::group(['middleware'=>['member']], function() {
        Route::get('/home', [\App\Http\Controllers\MemberController::class, 'home']);
        Route::get('/logout', [\App\Http\Controllers\MemberController::class, 'logout']);
    });

});

 

参考文档:

https://www.cnblogs.com/caibaotimes/p/14482312.html
https://learnku.com/articles/3758/laravel-user-authentication-system
https://qa.1r1g.com/sf/ask/4044196201/
https://learnku.com/docs/laravel/8.x/authentication/9381

 

【版权申明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权) https://www.cnblogs.com/facetwitter/p/15798378.html

上一篇:JavaTPoint 计算机科学教程【翻译完成】


下一篇:Linux下为当前用户添加 PYTHONPATH 环境变量