我想基本验证如果用户是管理员然后请求下一个,否则重定向到主页
user.php的
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password','role_id','is_active','photo_id',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function role(){
return $this->belongsTo('App\Role');
}
public function photo(){
return $this->belongsTo('App\Photo');
}
public function isAdmin(){
if ($this->role()->name=="administrator"){
return true;
}
return false;
}
}
最后一个函数是isAdmin()
Admin.php (这是中间件)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Admin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::check()){
if (Auth::user()->isAdmin()){
return $next($request);
}
}
return redirect('/');
}
}
routes.php文件
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin',function(){
return view('admin.index');
});
Route::group(['middleware'=>'admin'],function(){
Route::resource('/admin/users','AdminUsersController');
});
Route::auth();
Route::get('/home', 'HomeController@index');
**它显示我错误!**
Admin.php第21行中的FatalErrorException: 在null
上调用成员函数isAdmin()
我还在kernel.php中添加了'admin' =>\App\Http\Middleware\Admin::class,
并在Admin.php中导入了该类
PLZ ME,IAM STUCK !!!!!!!!
答案 0 :(得分:2)
这是因为没有用户会话。中间件仅在用户登录时有效。所以你需要先登录,然后检查中间件
答案 1 :(得分:0)
请尝试此操作:在User.php模型上将您的方法更改为 静态 。
static function isAdmin(){
if ($this->role()->name=="administrator"){
return true;
}
return false;
}
下一步:修改它应该工作的中间件。
<?php
namespace App\Http\Middleware;
use Closure;
class Admin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (auth()->check()){
if (\Admin::isAdmin()){
return $next($request);
}
}
return abort(404); //redirect the user to not found page.
}
}