dimanche 15 avril 2018

Protecting Routes with Role Permissions using middleware Laravel

I have a multilevel members website and need to protect my routes in the web.php file in Laravel 5.5.

I have a column on my users table called role_id.

In role_id is the following values

  • NULL (For New Users)
  • 1 (For Owner)
  • 2 (For Admin)
  • 3 (For Moderators)
  • 4 (For Banned Users)

I was trying to do it with a simple IF statement

if (Auth::user()->role_id != '2'):
    return view('home');
    else:
//ADMIN ROUTES
    Route::get('/admin','AdminController@index')->name('admin');
endif;

if (Auth::user()->role_id != '1'):
    return view('home');
    else:
//OWNER ROUTES
    Route::get('/admin','OwnerController@index')->name('owner');
endif;
ETC....

But get Error Trying to get property of non-object. Also probably not the best way to do that.

So I read about doing it with MIDDLEWARE like this: (Looks much better)

Route::group(['middleware' => ['auth', 'admin']], function() {
    // put all your admin routes here
});

Route::group(['middleware' => ['auth', 'owner']], function() {
    // put all your owner user routes here
});

But it didn't explain how to add the Middleware. Would I have to create 5 different Middleware files for each group similar to file I found:

use Illuminate\Contracts\Auth\Guard;

class Admin
{
    protected $auth;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    public function handle($request, Closure $next)
    {
        if($this->auth->user()->role_id != '2') {
            return redirect()->view('home');
        }
        return $next($request);        
    }
}

Could someone lend a helping hand and explain how to write the correct middleware to achieve this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire