2014-09-13 44 views
0

我的文章和標籤表之間有多對多關係,並且希望用戶在創建/編輯文章表單中輸入標籤。我使用Ardent我的驗證,並在我的文章模型如下:使用Laravel驗證多對多關係輸入字段

class Article extends Ardent { 

    use PresentableTrait; 
    protected $presenter = 'presenters\ArticlePresenter'; 

    protected $fillable = ['category_id', 'title', 'description', 'content', 'published']; 

    public static $rules = array(
    'title' => 'required', 
    'description' => 'required', 
    'content' => 'required|min:250', 
    'category_id' => 'exists:categories,id', 
    'tags' => 'required' 
); 

    public function tags() 
    { 
    return $this->belongsToMany('Tag', 'article_tag', 'article_id', 'tag_id'); 
    } 

} 

我的表單輸入:

<div class="form-group @if ($errors->has('tags')) has-error @endif"> 
    {{ Form::label('tags', 'Tags') }} 
    @if(!isset($article)) 
     {{ Form::text('tags', null, array('class' => 'form-control')) }} 
    @else 
     {{ Form::text('tags', $article->present()->implodeTags, array('class' => 'form-control')) }} 
    @endif 
    @if ($errors->has('tags')) <p class="help-block">{{ $errors->first('tags') }}</p> @endif 
</div> 

但即使我在標籤字段中輸入一些驗證失敗,這是爲什麼那?

回答

0

我找到了原因;變量tags未被傳遞給Ardent

爲了固定此我添加tagsfillable變量:

protected $fillable = ['category_id', 'title', 'description', 'content', 'published', 'tags']; 

另外添加以下代碼,在Ardent readme file解釋:

public $autoPurgeRedundantAttributes = true; 

function __construct($attributes = array()) { 
    parent::__construct($attributes); 

    $this->purgeFilters[] = function($key) { 
     $purge = array('tags'); 
     return ! in_array($key, $purge); 
    }; 
} 
+0

第一部分(將'標籤'添加到可填充數組中)是否足夠?我試圖讓這個在我的情況下工作,我無法。 – 2014-10-23 07:28:32

+0

這取決於,在我的情況下,我實際上並沒有'article'表中的'tags'字段。我只需要將它傳遞給Ardent。後面的代碼清除'tags'變量,因此它不會將它寫入表中。 – 2014-10-23 08:30:19

+0

你誤會了,但沒關係:)我在主表中沒有外部字段,但是我使用的是laravel管理員,它在保存之前取消了任何「外部」數據字段,從而阻止了它的工作。 – 2014-10-23 17:21:16