2015-12-01 63 views
1

所以我想在laravel 5.1中創建一個全局範圍,但只是繼續得到以下錯誤Trait 'Eloquent\Scopes\DependentTypeTrait' not foundLaravel 5.1問題實施全球範圍

這裏是我的代碼:

應用程序\型號\雄辯\作用域\ DependentTypeTrait.php:

<?php namespace App\Models\Eloquent\Scopes; 

trait DependentTypeTrait { 

    /** 
    * Boot the Active Events trait for a model. 
    * 
    * @return void 
    */ 
    public static function bootDependentTypeTrait() 
    { 
     static::addGlobalScope(new DependentTypeScope); 
    } 

} 

應用程序\型號\雄辯\作用域\ DependentTypeScope.php:

<?php namespace App\Models\Eloquent\Scopes; 

use Illuminate\Database\Eloquent\ScopeInterface; 
use Illuminate\Database\Eloquent\Builder; 

class DependentTypeScope implements ScopeInterface 
{ 

    public function apply(Builder $builder) 
    { 
     $builder->where('vip_type_id', 2); 
    } 

    public function remove(Builder $builder) 
    { 

     $query = $builder->getQuery(); 

     // here you remove the where close to allow developer load 
     // without your global scope condition 

     foreach ((array) $query->wheres as $key => $where) { 

      if ($where['column'] == 'vip_type_id') { 

       unset($query->wheres[$key]); 

       $query->wheres = array_values($query->wheres); 
      } 
     } 
    } 
} 

App \ Models \ Dependent.php:

<?php namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 
use Eloquent\Scopes\DependentTypeTrait; 

class Dependent extends Model 
{ 

    use DependentTypeTrait; 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = '<my table name>'; 

    /** 
    * The actual primary key for the model. 
    * 
    * @var string 
    */ 
    protected $primaryKey = '<my primary key>'; 

} 

我覺得我的命名空間正確,但它仍然說它無法找到屬性....任何想法?

回答

1

我想嘗試導入您的DependentTypeTrait當你使用命名空間錯誤:

<?php namespace App\Models\Eloquent\Scopes; 

trait DependentTypeTrait { //... 

然後你在App\Models\Dependent使用它:

use Eloquent\Scopes\DependentTypeTrait; 

這些名稱不匹配。試試這個:

use App\Models\Eloquent\Scopes\DependentTypeTrait; 

或者你可以修改你composer.json改變Eloquent命名空間是怎樣自動加載:

"autoload": { 
    "psr-4": { 
     "Eloquent\\": "app/Models/Eloquent" 
    } 
}, 

而且不要忘了轉儲磁帶自動加載機:$ composer dump-autoload

雖然具體因爲你使用的名字是Eloquent,這在Laravel中是無處不在的,即使你爲自己節省了一些打字工作,我也不會自己走這條路。 Laravel本身使用命名空間Illuminate\Database\Eloquent,因此您現在可能不會遇到衝突,但是如果泰勒改變了某些情況,或者使用了踩踏它的第三方庫,則存在這種可能性。

+0

你是對的!我假設,因爲該模型上的名稱空間是App \ Namespace,我不必在使用中添加此... –