Search code examples
phplaravel-5eloquentcartalyst-sentinel

eloquent relations with extend user model sentinel laravel package


I have a class User that extends

<?php

namespace App;

class User extends \Cartalyst\Sentinel\Users\EloquentUser
{
    public function chalets(){
        return $this->hasMany('App\Chalet');
    }
}

and i have Chalet Class

class Chalet extends Model
{
    protected $fillable = [
        'name', 'description',
    ];
public function user(){
        return $this->belongsTo('App\User');
    }
}

And i have method to add chalet by user :

public function postCreateChalet(Request $request){
        $chalet = new Chalet([
            'name' => $request->input('name'),
            'description' => $request->input('description')
        ]);
        Sentinel::getUserRepository()->setModel('App\User');
        $user = Sentinel::getUser();
        $user->chalets()->save($chalet);
        return ('chalet has created');
    }

and its give me an error :

BadMethodCallException
Call to undefined method Cartalyst\Sentinel\Users\EloquentUser::chalets()

Is it a right way to extend User class ?

I have searched for ways to extend the User class. I found this question:Model Inheritance in Laravel didn't help me though.

I'm using Laravel 5.7


Solution

  • The exception you're getting indicates Sentinel is still referring to the default stock Sentinel's EloquentUser model. Make sure you point to your extended user model with the published Sentinel configurations.

    1. Run the below command

      php artisan vendor:publish --provider="Cartalyst\Sentinel\Laravel\SentinelServiceProvider"
      
    2. Open up the published config file at 'config\cartalyst.sentinel.php'

    3. Modify it from the below content: 'users' => [ 'model' => 'Cartalyst\Sentinel\Users\EloquentUser', ], to: 'users' => [ 'model' => 'App\User', ],

    For more information, refer to https://github.com/cartalyst/sentinel/wiki/Extending-Sentinel

    You won't need the following line after you configured it via config:

    Sentinel::getUserRepository()->setModel('App\User');