1

I have a many-to-many relationship between my articles and tags table, and want to require the user to input tags in the create/edit article form. I am using Ardent for my validation and have the following in my article model:

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');
  }

}

My form input:

<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>

But the validation fails even if I enter something in the tags field, why is that?

Thomas Jensen
  • 2,138
  • 2
  • 25
  • 48

2 Answers2

0

I found the cause of this; the tags variable wasn't being passed to Ardent.

To fixed this I added the tags to the fillable variable:

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

Further I added the following code, explained in the 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);
    };
}
Thomas Jensen
  • 2,138
  • 2
  • 25
  • 48
  • Would the first part (adding 'tags' to the fillable array) be enough? I'm trying to get this to work in my situation, and am unable to. – Mike T Oct 23 '14 at 07:28
  • That depends, in my case I do not actually have a `tags` field in the `article` table. I only need to pass it to Ardent. The latter code purges the `tags` variable so it does not try to write it to the table. – Thomas Jensen Oct 23 '14 at 08:30
  • You misunderstood, but it's ok :) I also do not have my external field in the main table, but I'm using laravel administrator, which unsets any "external" data fields prior to saving, preventing this from working. – Mike T Oct 23 '14 at 17:21
0

It's now possible to validate relationship data in the latest version of Administrator.

treeface
  • 13,270
  • 4
  • 51
  • 57