Search code examples
phplaravelauthenticationroutesmiddleware

Create middleware for admin user with laravel


I build an simple app and I have Users, but some users need to have admin privilegies, so I try to create this:

  1. First at migration file I add boolean type - admin:

    public function up()

     {
            Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->boolean('admin');
                $table->string('username');
                $table->string('email')->unique();
                $table->string('password', 60);
                $table->rememberToken();
                $table->timestamps();
            });
        }
    

after that I create new middleware:

class RedirectIfNotAManager
{

    public function handle($request, Closure $next)
    {
        if (! $request->user()->IsATeamManager()){

            return redirect('articles');

        }
        return $next($request);
    }
}

offcource Now I need to create function IsATeamManager() at User model file:

public function IsATeamManager(){
        if ($this->is('admin') {
            return true;
        }
        return false;

    }

at Kernel.php I add manager:

 protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'manager' => \App\Http\Middleware\RedirectIfNotAManager::class,

    ];

At route I add:

Route::get('foo', ['middleware'=>'manager', function(){

    return 'This Page is Only for Managers';

}]);

Manually at phpMyAdmin I change the user admin column for some users at '1'... I log as that user,

But when I try to go at: localhost:8888/foo I get this error:

BadMethodCallException in Builder.php line 2071: Call to undefined method Illuminate\Database\Query\Builder::is()

What I also try is to chech is authenticated user admin when i make request so I write:

public function store(Requests\ArticleRequest $request)
    {
        $article = new Article($request->all());

        Auth::user()->is('admin')->articles()->save($article);

        return redirect('articles');
    }

but that doesn work and I dont know why... so my request is if authenticated users have admin column true then save article...

What you suggest? How to implement user admin at my app?


Solution

  • I think you should replace this:

    Auth::user()->is('admin')->articles()->save($article);
    

    with this:

    Auth::user()->where('admin', 1)->articles()->save($article);