laravel 5.0 实现默认的多表auth认证,如前后台表


不要看这个文章了。写的根本就不对!

不要看这个文章了。写的根本就不对!

不要看这个文章了。写的根本就不对!

研究一翻,竟然成了,不过是懵懵懂懂啊。。

目的是实现前后台用户的分别登录,这样就对应两个表了。。laravel5默认是对应users表,我再建立一个admins表,用来后台登录。
直接上吧,最主要就是有两个config设置:

	
	Config::set('auth.model', 'App\Model\admin\admin');
	Config::set('auth.table', 'admins');

一个是修改登录模型,一个是对应的认证表。


1.建立中间件 make:middleware AdminAuth

然后记得在你的路由组中添加这人过滤中间件

这是用来过滤的,没有登录就跳转到登录页面。

	public function handle($request, Closure $next)
	{
		//修改一下auth的默认登录表
		//echo Auth::getFacadeApplication()->config['auth']['table'];
		Config::set('auth.model', 'App\Model\admin\admin');
		Config::set('auth.table', 'admins');
		//dd(Auth::getFacadeApplication()->config['auth']['table']);
 		if(Auth::check()){
			//已经登录	
			//dd('s');	
		}
		else{
			//还没有登录
			//dd('not login');
			return redirect()->guest('admin/login');
		}
		
		return $next($request);
	}

修改Kernel文件中 $routeMiddleware的数组,添加命名我们的中间件

		//后台管理的中间件
		'adminauth' => 'App\Http\Middleware\AdminAuth'

2.实现登录验证操作

public function loginHandle()
	{
		//下边两个设置很重要
		Config::set('auth.model', 'App\Model\admin\admin');
		Config::set('auth.table', 'admins');
		//
		$username = Input::get('username');
		$password = Input::get('password');
		$rememberme = true;
		if (Input::get('rememberme')){
			$rememberme = true;
		}
		else{
			$rememberme = false;
		}
		if(Auth::attempt([
			'username' => $username,'password' => $password
		],$rememberme))				
		{
			//登录成功
			return redirect(action('admin\AdminController@index'));
		}
		else {
			//登录失败
			return redirect(action('admin\AdminController@login'))
			->withErrors("用户名或者密码不正确");
		}
		//
	}

3.建立并修改 admin模型。因为用artisan生成的默认模型其实是没有验证功能的,所以我们生成后,直接照搬 框架自带的 users 模型,然后修改一下

protected $table = 'admins';

附我的admin 模型

<?php namespace App\Model\admin;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class Admin extends Model implements AuthenticatableContract, CanResetPasswordContract {

	//
	use Authenticatable, CanResetPassword;
	
	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'admins';
	
	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = ['name', 'email', 'password'];
	
	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = ['password', 'remember_token'];
	
}

就好了。。

好像就是这样吧,你们试试,有问题留言。我这是ok了的。

7 comments

  1. 这个默认的认证,同一浏览器,是不是只能认证登录一个用户???
    比如,调用auth::logout,是不是所有用户都会退出,不管是前台,还是后台用户?

Leave a Reply