最近群里很多人文档,laravel如何做会员和管理两个身份登录,今天把教程分享一下
自定义用户表登录
认证是由 guards 和 providers 两部分构成的, defaults 配置是默认选择一个 guard 认证驱动,所以我们在这两个配置项中分别添加一个 admin 和 admins 选项。
<?php 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ], 'admins' => [ 'driver' => 'eloquent', 'model' => App\Models\Admin::class, ], ],
标红的是我们后添加的后台管理员登录身份
创建后台用户表和model
php artisan make:model Admin php artisan make:migration creaet_admins_table
在数据库迁移文件 _create_admins_table , 我们可以复制 users 迁移文件里的字段
Schema::create('admins', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email'); $table->string('password'); $table->rememberToken(); $table->timestamps(); });
执行php artisan migrate
生成临时数据
在 database/factories/ModelFactory.php, 添加如下数据:
$factory->define(App\Admin::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->name, 'password' => $password ?: $password = bcrypt('123456'), 'email' => $faker->email, 'remember_token' => str_random(10), ]; });
打开命令行输入:
php artisan tinker use App; factory(App\Admin::class,5)->create() //生成5条测试数据,你要几条就输入多少(Class,num)
更改 Admin 模型类
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class Admin extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; }
创建控制器
php artisan make:controller Admin/LoginController php artisan make:controller Admin/AdminController
内容版权声明:除非注明,否则皆为本站原创文章。