Search code examples
laravelauthenticationsmf

Set custom user details in laravel auth


I'm having smf forum where using smf_members table in db. There are fields like this:

array(32) {
  ["groups"]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    int(25)
  }
  ["possibly_robot"]=>
  bool(false)
  ["id"]=>
  string(2) "28"
  ["username"]=>
  string(7) "Milan95"
  ["name"]=>
  string(7) "Milan95"
  ["email"]=>
  string(16) "******"
  ["passwd"]=>
  string(40) "******"
  ["language"]=>
  string(18) "serbian_latin-utf8"
  ["is_guest"]=>
  &bool(false)
  ["is_admin"]=>
  &bool(true)
  ["theme"]=>
  string(1) "7"
  ["last_login"]=>
  string(10) "1576930811"
}

Also i have laravel model "User".

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;

    protected $fillable = [
        'real_name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];


    protected $table = 'smf_members';
    protected $primaryKey = 'id_member';
    public $timestamps = false;
}

But i can only acces that info when i call: User::find($id); then there is data from smf_members.

I can not find any way to put active session and data to User model and fields, from

 global $user_info;
 var_dump($user_info);

Where i'm getting data from first "code" there.

Thanks, please help :)


Solution

  • You can use eloquent accessors. Update your model to:

    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Spatie\Permission\Traits\HasRoles;
    
    class User extends Authenticatable
    {
        use Notifiable;
        use HasRoles;
    
        protected $fillable = [
            'real_name', 'email', 'password',
        ];
        protected $hidden = [
            'password', 'remember_token',
        ];
    
        // add this line if you're using api
        protected $appends = ['smf_info'];
    
    
        protected $table = 'smf_members';
        protected $primaryKey = 'id_member';
        public $timestamps = false;
    
        // add this block
        public function getSmfInfoAttribute()
        {
          return // your logic to find current user smf info
        }
    }
    

    Then you can access the attribute by User::find($id)->smf_info