0
votes

I have a dashboard view that shows certain contain depending on which user is viewing, whether it be an admin or just a regular user.

I can get my admins onto that page, but regular users aren't able to currently because of my middleware guard.

class DashboardController extends Controller {

    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    public function index()
    {
        return view('dashboard.index');
    }
}

The following code checks on each DashboardController call for auth:admins, but I want regular users to access this too, is there a way to check the auth middleware twice like so?

$this->middleware(['auth:admin','auth']);

So ideally it will check if you're an admin or just a regular auth user.

Also on my view page, when accessing properties of an admin I'm using:

{{ Auth::user()->admin_username }}

Is this normal? I have an admin Model but I'm still accessing it via Auth::user() which feels strange to me, shouldn't it be Auth::admin()->admin_username

2
did u find any solution for constructorRahul Tathod

2 Answers

0
votes

Accessing a particular page for users with differing roles is more suited for laravels gates and policy authorization mechanisms.

https://laravel.com/docs/5.5/authorization#writing-gates

These allow you to write fine tuned rules for each use case you have. Simple gates can be defined as closures within your application AuthServiceProvider. For example:

public function boot()
{
    $this->registerPolicies();

    Gate::define('access-dashboard', function ($user, $post) {
        return auth()->check() && (auth()->user()->hasRole('admin') || auth()->user()->hasRole('regular'));
    });
}

Then you can use the gate facade wherever necessary, for instance a controller method or constructor.

if (Gate::allows('access-dashboard', $model)) {
    // The current user can access dashboard, load their data
}

Alternatively use the can or cant helpers on the user model directly.

if (auth()->user()->can('access-dashboard')) {
    //
}

Of course, you can achieve similar via middleware, the advantage of using the above is you can authorize actions at specific points in your code as well as reusability.

As for for last question, as you have it written is correct.

{{ Auth::user()->admin_username }}

Auth::user() or auth()->user() simply returns the currently authenticated user, regardless of their role.

0
votes

Policies will never work without auth middleware