因為有朋友在問我 [ 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 衝突
由於 EntrustUserTrait和 SoftDeletes兩個 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 衝突
解決辦法是將 EntrustUserTrait的 can方法改一個別名,然後使用 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