Search code examples
phplaravelrolesrelation

BadMethodCallException Call to undefined method App\Models\User::role()


I code a attendance employee system to load reports of time employers
i got below error
What should I do to solve this problem?

BadMethodCallException
Call to undefined method App\Models\User::role()
Did you mean App\Models\User::only() ?

my user.php model:

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;

    use Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

   

   
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

   
    protected $appends = [
        'profile_photo_url',
    ];
}

Report Controller

        $employees = User::whereHas('role', function ($query) {
            $query->where('employee');
        })
            ->get();
        $dateRange = $reportService->generateDateRange();

        $timeEntries = $reportService->generateReport($request->input('employee'));
        if ($timeEntries) {
            $chart = new LaravelChart([
                'chart_title'           => 'Hours of work per day',
                'chart_type'            => 'line',
                'report_type'           => 'group_by_date',
                'model'                 => 'App\\TimeEntry',
                'group_by_field'        => 'time_start',
                'group_by_period'       => 'day',
                'aggregate_function'    => 'sum',
                'aggregate_field'       => 'total_time_chart',
                'column_class'          => 'col-md-8',
                'continuous_time'       => true,
            ]);
        } else {
            $chart = NULL;
        }

       

Solution

  • as per the discussion, there is no roles table so you can't check using User::whereHas('role') instead of that, you should use the following line

    $employees = User::whereRole('employee')->get();
    

    also, I have noticed that you haven't added role in fillable, you should add role to protected $fillable in order to consider that column for performing operations like create and save.