解决 Entrust 的 Trait 冲突

因为有朋友在问我 [here], 而我之前也正好遇到过,所以记录下。

当使用的多个 trait 中包含了相同的方法名,将会发生冲突,冲突错误信息如下

FatalErrorException in User.php line 43:
Trait method xxxxxx has not been applied, because there are collisions with other trait methods on App\Http\models\User

和 SoftDeletes 的 restore 冲突

由于 EntrustUserTraitSoftDeletes 两个 trait 都包含 restore 方法,所以当我们对用户 Model 使用软删除的时候同时集成 Entrust 的时候就会导致冲突。

解决方法就是引用两个 trait 时为 restore 方法设置别名,然后重写一个 restore 方法,分别调用两个 restore 方法。代码如下:

class User extends Model implements AuthenticatableInterface
{
    use Authenticatable;
    use EntrustUserTrait { restore as private restoreA; }
    use SoftDeletes { restore as private restoreB; }

    /**
     * 解决 EntrustUserTrait 和 SoftDeletes 冲突
     */
    public function restore()
    {
        $this->restoreA();
        $this->restoreB();
    }
}

和 Authorizable 的 can 冲突

解决办法是将 EntrustUserTraitcan 方法改一个别名,然后使用 Authorizable 中的 can,代码如下

use Authenticatable, CanResetPassword, PresentableTrait, Authorizable, EntrustUserTrait {
    EntrustUserTrait::can as may;
    Authorizable::can insteadof EntrustUserTrait;
}

参考: Laravel 5.1.11 - Trait method can has not been applied, because there are collisions with other trait methods on App\User

本帖已被设为精华帖!
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 6

两年后新手踩坑,感谢LC大佬的解决办法

6年前 评论

good

6年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!