Reputation: 1868
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
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?
Upvotes: 2
Views: 14576
Reputation: 26
web.php
Route::group(['middleware' => ['auth', 'admin']], function() {
Route::get('/admin/dashboard', function(){
return view('admin.dashboard');
});
});
into protected $routeMiddleware of Kernel.php
'admin' => \App\Http\Middleware\AdminMiddleware::class,
AdminMiddleware.php
$user = Auth::user();
if($user->role == 'admin'){
return $next($request);
} else
// abort(403, 'Wrong Accept Header');
return new Response(view('notauthorized')->with('role', 'admin'));
}
admin, moderators, owner, banned_user will be value of user_type/role column of user table.
or you can use user_type_id
or role_id
instead of user_type_name
or role_type
Don't forget to add
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Response;
just under the
use Closure;
of your Middleware
You can also do it with other ways like Gate, let me know if you need it. :)
Upvotes: 1
Reputation: 126
Error Trying to get property of non-object. Can be found if user not logged in yet.
Before u check
if (Auth::user()->role_id != '2'):
u should make sure that user is logged in with
Auth::check()
first...
Upvotes: 0
Reputation: 1815
Like this example:
Route::get('/cart/payment', 'CartController@getcartpayment')->middleware('checkAuth');
$user = Sentinel::findById($user_id);
$role= $user->role();
Upvotes: 0