Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel use custom USER-Model in package

I´ve developed a package stored in LaravelRoot/packages/myname/project/ in Laravel.

Inside my package i´ll have to use an extended user-model containing a relationship not mentioned in the default usermodel.

Now here is my question: How can i override the default User-Model inside my package?


More details:

If i receive the current user via Auth::user() inside my package i´ll receive an object using the default App\User.

I have extended this model containing now a new relationfunction, stored in LaravelRoot/packages/myname/project/src/App/Models/User (namespace: Myname\Myproject\App\Models). Here´s my relation-function:

/**
 * The roles that belong to the user.
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function roles()
{
    return $this->belongsToMany(Role::class)->withTimestamps();
}

This relation is only used in my package, so i don´t want to store this function inside the default App\User. Is it possible to receive an object of my extended usermodel using Auth::user() in my package or do i have to receive this manually each time i need this one?

like image 857
NeronNF Avatar asked Jan 09 '18 15:01

NeronNF


1 Answers

I think, the easiest way is to make your package model via extending of App\User model. You need just to open config/auth.php and to setup your model class.

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => Project\Models\User::class,
    ],

You will get correct model via Auth::user().

like image 120
shukshin.ivan Avatar answered Oct 05 '22 18:10

shukshin.ivan