Search code examples
phplaravellaravel-socialite

Laravel Auth User add custom data


We are currently working on an application with a Google Login with Laravel with Socialite. We have a Auth user who gets a permission number ex. 264. We have made a function which returns an array with all binary numbers this permission number is made off.

Because calling this function every single time a page loads may be kinda heavy, we thought of adding this once when the Auth::user() is created. We thought of adding a custom constructor in the Model, but we can't make it work.

function __construct($attributes = array()) {
  parent::__construct($attributes);
  $this->permissionsArray = PermissionHelper::permissionConverter($this->permissions);
}

But we can't get it to work, $this doesn't have values when calling this function.

TLDR; Directly after making the Auth user I want to call the permissionConverter function and save the data to the user so we can use it more often. Any suggestions on how to do this?

EDIT: I checked all answers out today, succeeded with one of them, but I assumed Laravel put the authenticated user in the SESSION or something. I found out it doesn't and it gets all the data from the database every request. We couldn't do what we requested for unfortunately. So I just had to refactor the script and make it as efficient as possible (although it became a bit less readable for less experienced programmers).

Thanks for the help :D


Solution

  • Maybe you can use this solution ? https://stackoverflow.com/a/25949698/7065748

    Create a on the User Eloquent model a boot method with

    class User extends BaseModel {
      public static function boot() {
        static::creating(function($model) {
          $model->permissionsArray = PermissionHelper::permissionConverter($model->permissions);
        });
        // do the same for update (updating) if necessary
      }
    }
    

    Can't you just use this method ?

    If new user:

    $user = new User(); // or User:create(['...']) directly
    $user->name = 'toto';
    // and all other data
    

    or

    $user = Auth::user();
    

    then

    $user->permissionsArray = PermissionHelper::permissionConverter($user->permissions);
    $user->save();