【问题标题】:Laravel - Call to undefined method in repositoryLaravel - 调用存储库中未定义的方法
【发布时间】:2016-09-15 21:54:37
【问题描述】:

我创建了一个EloquentUserRepository 以保持我的代码简洁和可扩展。

这是我的EloquentUserRepository

namespace App\Repositories\User;

use App\Models\Role;
use App\Repositories\EloquentRepository;

class EloquentUserRepository extends EloquentRepository implements UserContract
{

    /**
     * Get class name
     *
     * @return string
     */
    protected function getModelName()
    {
        return 'App\Models\User';
    }

    /**
     * Check if user has the given role.
     * Could be a string or a collection
     *
     * @param $role
     */
    public function hasRole($role)
    {
        if (is_string($role)) {
            return $this->roles->contains('name', $role);
        }

        // This will remove from the roles all the roles that do not match the given one.
        // If the result is empty the user do not have that role.
        return $role->intersect($this->roles)->count();
    }

    /**
     * Assign the role to the user
     *
     * @param Role $role
     */
    public function assignRole(Role $role)
    {
        return $this->model->roles()->save($role);
    }
}

但是当我在我的播种机中使用它时:

use App\Models\Role;
use App\Models\User;
use App\Repositories\User\EloquentUserRepository;
use Illuminate\Database\Seeder;

class AdminSeeder extends Seeder
{

    /**
     * @var EloquentUserRepository
     */
    private $userRepository;

    /**
     * AdminSeeder constructor.
     *
     * @param EloquentUserRepository $userRepository
     */
    public function __construct(EloquentUserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    /**
     * Run the database seeds.
     *
     */
    public function run()
    {
        $admins = [
            [
                'first_name' => 'Christian',
                'last_name'  => 'Giupponi',
                'email'      => 'christian.giupponi@example.com',
                'password'   => 'sviluppo'
            ]
        ];
        $adminRole = Role::where('name', 'admin')->get()->first();

        foreach($admins as $admin){
            $a = $this->userRepository->create($admin);
            $a->assignRole($adminRole);
        }
    }
}

我明白了:

BadMethodCallException] 调用未定义的方法 Illuminate\Database\Query\Builder::assignRole()

这是create 方法:

/**
     * Create new resource
     *
     * @param array $data
     * @return mixed
     */
    public function create(array $data)
    {
        return $this->model->create($data);
    }

如果我dd 我得到User 模型:

App\Models\User {#605
  #fillable: array:4 [
    0 => "first_name"
    1 => "last_name"
    2 => "email"
    3 => "password"
  ]
  #hidden: array:2 [
    0 => "password"
    1 => "remember_token"
  ]
  #dates: array:1 [
    0 => "deleted_at"
  ]
  #connection: null
  #table: null
  #primaryKey: "id"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:7 [
    "first_name" => "Christian"
    "last_name" => "Giupponi"
    "email" => "christian.giupponi@example.com"
    "password" => "$2y$10$sQfyoGVJxzsrs71kMW9Ul.PZ/EWbQSChhurIevwEPwwxdPYKETFOO"
    "updated_at" => "2016-05-19 07:12:18"
    "created_at" => "2016-05-19 07:12:18"
    "id" => 1
  ]
  #original: array:7 [
    "first_name" => "Christian"
    "last_name" => "Giupponi"
    "email" => "christian.giupponi@example.com"
    "password" => "$2y$10$sQfyoGVJxzsrs71kMW9Ul.PZ/EWbQSChhurIevwEPwwxdPYKETFOO"
    "updated_at" => "2016-05-19 07:12:18"
    "created_at" => "2016-05-19 07:12:18"
    "id" => 1
  ]
  #relations: []
  #visible: []
  #appends: []
  #guarded: array:1 [
    0 => "*"
  ]
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: true
  #forceDeleting: false
}

编辑:
$a 中的Log 迭代:

[2016-05-19 07:22:12] local.DEBUG: App\Models\User Object
(
    [fillable:protected] => Array
        (
            [0] => first_name
            [1] => last_name
            [2] => email
            [3] => password
        )

    [hidden:protected] => Array
        (
            [0] => password
            [1] => remember_token
        )

    [dates:protected] => Array
        (
            [0] => deleted_at
        )

    [connection:protected] => 
    [table:protected] => 
    [primaryKey:protected] => id
    [perPage:protected] => 15
    [incrementing] => 1
    [timestamps] => 1
    [attributes:protected] => Array
        (
            [first_name] => Christian
            [last_name] => Giupponi
            [email] => christian.giupponi@example.com
            [password] => $2y$10$aW/rP7oHqH0/mj7RfYBR9OdvxRCEXiYLOVCIvfY1BHGNCuBNdcy/i
            [updated_at] => 2016-05-19 07:22:12
            [created_at] => 2016-05-19 07:22:12
            [id] => 1
        )

    [original:protected] => Array
        (
            [first_name] => Christian
            [last_name] => Giupponi
            [email] => christian.giupponi@example.com
            [password] => $2y$10$aW/rP7oHqH0/mj7RfYBR9OdvxRCEXiYLOVCIvfY1BHGNCuBNdcy/i
            [updated_at] => 2016-05-19 07:22:12
            [created_at] => 2016-05-19 07:22:12
            [id] => 1
        )

    [relations:protected] => Array
        (
        )

    [visible:protected] => Array
        (
        )

    [appends:protected] => Array
        (
        )

    [guarded:protected] => Array
        (
            [0] => *
        )

    [dateFormat:protected] => 
    [casts:protected] => Array
        (
        )

    [touches:protected] => Array
        (
        )

    [observables:protected] => Array
        (
        )

    [with:protected] => Array
        (
        )

    [morphClass:protected] => 
    [exists] => 1
    [wasRecentlyCreated] => 1
    [forceDeleting:protected] => 
)

【问题讨论】:

  • EloquentUserRepository::create 返回什么?这似乎是Illuminate\Database\Query\Builder 的一个实例
  • 它返回App\Models\User
  • 从错误看来,它试图在Illuminate\Database\Query\Builder 上调用assignRole,所以也许在循环的迭代中出现了问题?您可以尝试在assignRole 调用之前的每次迭代中记录$a 的内容吗?即:Log::debug( print_r($a, true) );
  • 用日志更新了问题
  • 我看到assignRoleEloquentUserRepository 类的一个方法。因此,如果$aApp\Models\User 的一个实例,则$a->assignRole() 不存在。或者你也有App\Models\User::assignRole 方法?

标签: php laravel laravel-5 laravel-5.2


【解决方案1】:

问题在于assignRoleEloquentUserRepository 类的一个方法。因此,如果$aApp\Models\User 的一个实例,则$a->assignRole() 不存在。

如果要通过repository分配角色,需要调用repository上的方法:

$this->userRepository->assignRole($adminRole);

假设该方法将获得对实际User 模型的访问权并将角色分配给它。如果不是这样,您可以将实际的Model 作为参数传递,并在方法中分配角色:

//pass both role and model to the repository
public function assignRole(Role $role, Model $user)
{
    //here assign the role to the user
}

所以你的代码将是:

$a = $this->userRepository->create($admin);
$this->userRepository->assignRole($adminRole, $a);

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 2020-04-27
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2016-06-05
    • 2016-09-03
    相关资源
    最近更新 更多