1

I have a Category Controller which checks if user is logged in

class CategoryController extends Controller
{
     public function __construct() {
        $this->middleware('auth');

    }
    ...

My category routes are :

//Category Controller
Route::get('admin/category/{category}/edit', ['uses'=>'categoryController@edit','as'=>'admin.category.edit']);
Route::put('admin/category/{category}', ['uses'=>'categoryController@update','as'=>'admin.category.update']);
Route::get('admin/category/{category}', ['uses'=>'categoryController@show','as'=>'admin.category.show']);
Route::delete('admin/category/{category}', ['uses'=>'categoryController@destroy','as'=>'admin.category.destroy']);
Route::get('admin/category/create', ['uses'=>'categoryController@create','as'=>'admin.category.create']);
Route::get('admin/category', ['uses'=>'categoryController@index','as'=>'admin.category.index']);
Route::post('admin/category', ['uses'=>'categoryController@store','as'=>'admin.category.store']);

Is there a way to give access to these views to only specific user?

For example if user email is admin123@gmail.com then he is allowed to go to those view.

I know I can check like this

if(Auth::user()->email == 'admin123@gmail.com')
{
   dd('admin Logged in');
}

But this is possible if i go to individual view and put all my content in the if statement.

Is there way to handle this in controller.

Thanks.

Phoenix
  • 332
  • 2
  • 9
  • 32

3 Answers3

0

You can use the middlewares for these kinds of work.

From the docs

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Amit Gupta
  • 17,072
  • 4
  • 41
  • 53
0

You should restrict users by route groups. Use middleware for that.

However, if you have complicated logic, sometimes you may want to check if user is admin in controller, model and other classes. In this case you can create global helper isAdmin() and use it for simple checks. Examples:

if (isAdmin()) {
    // Do something
}

{{ isAdmin() ? 'active' : '' }}
Community
  • 1
  • 1
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

A better way to define user role is like 0 for admin, 1 for user, 2 for member.
Then you can check the user role like:

if(Auth::check())
{
  if(Auth::User()->user_type == 0)
  {
    return view('admin_dashboard');
  }
  else if(Auth::User()->user_type == 1)
  {
    return view('user_dashboard');
  }
  else if(Auth::User()->user_type == 2)
  {
    return view('member_dashboard');
  }
}
Kerwin Sneijders
  • 750
  • 13
  • 33
Komal
  • 2,716
  • 3
  • 24
  • 32