Php – Call to a member function isAdmin() on null in laravel

fatal errorlaravel-5PHP

I want to basic authenticate if User is Admin then Request next otherwise redirect to homepage

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;
    }
}

last function is isAdmin()

Admin.php (this is middleware):

<?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');

I get the following error:

FatalErrorException in Admin.php line 21:
Call to a member function isAdmin() on null

I also added 'admin' =>\App\Http\Middleware\Admin::class, in kernel.php and imported the class in Admin.php.

Best Answer

This is because of no user session. Middleware works only when user is login. So you need to login first and then check for middleware

Related Topic