1

I am currently trying to assign any guest the role 'Guest' so that they can have permissions. I currently have the following code, which is apart of some middleware, this seems to be the wrong place to have it, I would assume there is a much better place, I have tried using a service provider, however I couldn't attach the group

 if($this->auth->guest())
    {
        $user = new User();
        $user->username = 'Guest';

        $role = Role::where('name', '=', 'guest')
                ->with('perms')
                ->first();


        $user->perms = new Collection();
        $user->perms->add($role);

        $perms = explode('|', $permissions);

        foreach($user->perms as $p) {
            foreach($p->perms as $pp) {
                foreach($perms as $perm) {
                    if($perm === $pp->name)
                        return $next($request);
                }
            }
        }
    }

As you can see this is very specific to middleware, Ideally I want to attack the role at the first possible instance so it can be used in any part of the application

kenorb
  • 155,785
  • 88
  • 678
  • 743
Ian
  • 3,539
  • 4
  • 27
  • 48

2 Answers2

0

just use sessions in this case

  session::put('role',$role);

and in the view

 @if(Session::has('role') == 'whatever') 
 // show this content

same goes for permissions add an array of perms to the session then use in_array

Achraf Khouadja
  • 6,119
  • 4
  • 27
  • 39
0

I think that the place is right, but remember that you are executing this validation on every request, it looks heavy. So, why not using session or cache?

Using session:

if($this->auth->guest()){
    $userPerms = [];

    if (\Session::has('permissions')){
        $userPerms = \Session::get('permissions');
    }
    else{
        $user = new User();
        $user->username = 'Guest';
        // the rest of your code here...
        $userPerms = $user->perms;

        // update the session the first time
        \Session::put('permissions', userPerms)
    }

    // comparison here
}

You can apply the same logic using Cache provider.

manix
  • 14,537
  • 11
  • 70
  • 107