am new to Laravel
I have set up permissions and roles inside my application, and assigned these to users - however when I try to use hasRole or hasAnyRole it isn't working for me.
Here is my middleware:
namespace App\Http\Middleware;
use Closure;
use Auth;
class AccessAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user()->hasRoles('Admin')){
return $next($request);
}
return redirect('home');
}
}
<?php
Role Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users(){
return $this->belongsToMany('App\User');
}
}
User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User 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',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles(){
return $this->belongsToMany('App\Role');
}
public function hasAnyRoles($roles){
return null !== $this->roles()->whereIn('name',$roles)->first();
}
public function hasRoles($role){
return null !== $this->roles()->where('name',$role)->first();
}
}
which is producing this error:
FatalThrowableError (E_ERROR) Call to a member function hasRole() on null
Auth::user()
isnull
. Are you logged in? – Tim Lewis