之前做了一个单表的验证,今天来说说多表
首先我们来运行一下 php artisan make:auth
然后我们在views目录下建一个admin文件夹,将layouts文件夹包括里边的内容都复制过来,再将home.blade.php文件复制过来,重命名一下dashboard,再建一个auth文件夹,将login和register文件放进去,如下图
我们需要改一下admin下的layouts/app.blade.php文件,在这几个地方,后边会说明为什么改,为了方便看可以把dashboard.blade.php的标题改成Dashboard
还有auth文件夹里login和register表单的action也要改成前面加admin的路径,参照下边的路由
现在写路由文件,加入下面这段
代码语言:javascript复制Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuthAuthController@showLoginForm');
Route::post('/admin/login','AdminAuthAuthController@login');
Route::get('/admin/logout','AdminAuthAuthController@logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuthAuthController@showRegistrationForm');
Route::post('admin/register', 'AdminAuthAuthController@register');
Route::get('/admin', 'AdminController@index');
});
有了路由再写Controller和Model吧
运行 php artisan make:controller AdminAuth/AuthControler
代码语言:javascript复制<?php
namespace AppHttpControllersAdminAuth;
use AppUser;
use Validator;
use AppHttpControllersController;
use IlluminateFoundationAuthThrottlesLogins;
use IlluminateFoundationAuthAuthenticatesAndRegistersUsers;
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 = '/admin';
protected $redirectAfterLogout = '/admin/login';
protected $guard = 'admin';
/**
* Create a new authentication controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return IlluminateContractsValidationValidator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:admins',
'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']),
]);
}
}
php artisan make:controller AdminController
代码语言:javascript复制<?php
namespace AppHttpControllers;
use AppHttpRequests;
use IlluminateHttpRequest;
class AdminController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
//我们下边要修改Authenticate文件,另一个方法是你在这里可以写成admin,
//然后在kernal文件里$routeMiddleware注入一条admin的中间件,然后再建一个新的中间件
$this->middleware('auth:admin');
}
/**
* Show the application dashboard.
*
* @return IlluminateHttpResponse
*/
public function index()
{
return view('admin.dashboard');
}
}
php artisan make:model Admin
代码语言:javascript复制<?php
namespace App;
use IlluminateFoundationAuthUser as Authenticatable;
class Admin extends Authenticatable
{
/**
* 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:migration create_admins_table
代码语言:javascript复制<?php
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('admins');
}
}
生成数据库迁移php artisan migrate
然后再对Middleware/Authenticate文件进行修改
代码语言:javascript复制<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateSupportFacadesAuth;
class Authenticate
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
if($guard == 'admin'){
return redirect('admin/login');
}
return redirect()->guest('login');
}
}
return $next($request);
}
}
这样基本的内容都好了,由于我们想要的是管理员账号的登录,一般不存在注册,所以我们抛弃了注册功能,使用laravel的seed来写
运行 php artisan make:seed AdminsTableSeeder
代码语言:javascript复制<?php
use IlluminateDatabaseSeeder;
class AdminsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('admins')->insert([
'name' => 'admin',
'email' => 'admin@gmail.com',
'password' => bcrypt('secret'),
]);
}
}
在database里的seeds,更改DatabaseSeeder
代码语言:javascript复制<?php
use IlluminateDatabaseSeeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->call(AdminsTableSeeder::class);
}
}
我们运行php artisan db:seed
会在admins数据库写入一个登录账号是admin@gmail.com,密码是secret的用户
这样我们就可以直接尝试登录了,本人亲测有用,做这个结合了stackoverflow和youtobe的视频穷屌丝没钱买laravist