Skip to content
Advertisement

Laravel class not being found in a model

I am trying to get my project to use authorization roles to restrict users to certain featuers and I am following along with a tutorial. When I make a call to a class in my user.php file I am getting an error that the class AppRole can’t be found. I am not sure if it is a namespace issue but I can’t get to the bottom of it. I believe it is the roles function that is giving me this issue.

<?php

namespace EliteWorker;

use IlluminateNotificationsNotifiable;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'address', 'phone', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function roles() {
        return $this->belongsToMany('AppRole');
    }

    public function hasAnyRoles($roles){
        return null !== $this->roles()->whereIn('name', $roles)->first();
    }

    public function hasAnyRole($role){
        return null !== $this->roles()->where('name', $role)->first();
    }
}

Advertisement

Answer

You changed the namespace to EliteWorker so if the Model class Role is generated with Artisan, it’ll also have that namespace

public function roles()
{
  return $this->belongsToMany('EliteWorkerRole');
}

Note that you can also get the model base name by calling the class static property

public function roles()
{
  return $this->belongsToMany(Role::class);
}

No need to import it if it’s in the same namespace

Also note that the artisan command app:name has been removed in Laravel 6 to encourage developers to use the generic App namespace

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement