所以我看到很多类似的问题都被问到关于课程没有发现的错误,但除非我完全错过了一些明显的事情,否则我无法理解以下方法调用怎么看不到我的错误角色类和未找到类的结果:
$user->makeEmployee("admin")
这是我的makeEmployee()用户类:
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* Get the roles a user has
*/
public function roles()
{
return $this->belongsToMany('Role', 'users_roles');
}
/**
* Find out if User is an employee, based on if has any roles
*
* @return boolean
*/
public function isEmployee()
{
$roles = $this->roles->toArray();
return !empty($roles);
}
/**
* Find out if user has a specific role
*
* $return boolean
*/
public function hasRole($check)
{
return in_array($check, array_fetch($this->roles->toArray(), 'name'));
}
/**
* Get key in array with corresponding value
*
* @return int
*/
private function getIdInArray($array, $term)
{
foreach ($array as $key => $value) {
if ($value == $term) {
return $key;
}
}
throw new UnexpectedValueException;
}
/**
* Add roles to user to make them a concierge
*/
public function makeEmployee($title)
{
$assigned_roles = array();
$roles = array_fetch(Role::all()->toArray(), 'name');
switch ($title) {
case 'admin':
$assigned_roles[] = $this->getIdInArray($roles, 'create_message');
/*case 'member':
$assigned_roles[] = $this->getIdInArray($roles, 'create_customer');
case 'concierge':
$assigned_roles[] = $this->getIdInArray($roles, 'add_points');
$assigned_roles[] = $this->getIdInArray($roles, 'redeem_points');*/
break;
default:
throw new \Exception("The employee status entered does not exist");
}
$this->roles()->attach($assigned_roles);
}
}
这是我的角色课程:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $table = 'roles';
/**
* Set timestamps off
*/
public $timestamps = false;
/**
* Get users with a certain role
*/
public function users()
{
return $this->belongsToMany('User', 'users_roles');
}
}
如果两者都是相同的命名空间,我只能在Role
中使用User
吗?
我还尝试了clear-compile和composer dump-auto,并将Role
引用替换为App\Role
,并在顶部包含use App\Role
。我正在使用PHPStorm并且它可以捕获引用,并且我能够从用户代码跳转到Role
类定义。在此先感谢您的帮助!
答案 0 :(得分:2)
您没有传递类,Role
是在您正在扩展的类中调用的方法的字符串参数,因此您需要提供该类及其完整的命名空间。
return $this->belongsToMany('App\Role', 'users_roles');
答案 1 :(得分:2)
你应该做的
return $this->belongsToMany('App\Role', 'users_roles');
和dump-auto和dump-autoload都是一样的。