title: Laravel 5 custom validation rule for existing tags
body: <p>I'm searching for a cleaner way to validate tags when storing a Post. </p>
  
  <p>All of the input validation takes place within my custom request <code>StorePostRequest</code>. The problem is that I need to check whether the given tags exist in the database, only existing tags are allowed. The function <code>$request-&gt;input('tags')</code> returns a string with comma seperated values, for example: <code>Tag1,Tag2,Tag3</code>.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>/**
   * Store a newly created resource in storage.
   *
   * @param  StorePostRequest $request
   * @return Response
   */
  public function store(StorePostRequest $request)
  {
      //THIS PIECE OF CODE
      $tags = explode(',', $request-&gt;input('tags'));
      $tags = Tag::whereIn('title', $tags)-&gt;lists('id');
  
      if(count($tags) &lt; 1)
      {
          return redirect()-&gt;back()-&gt;withInput()-&gt;withErrors([ trans('tags.min') ]);
      }
      else if(count($tags) &gt; 5)
      {
          return redirect()-&gt;back()-&gt;withInput()-&gt;withErrors([ trans('tags.max') ]);
      }
      //TILL HERE
  
      $post = $request-&gt;user()-&gt;posts()-&gt;create([
          'slug'          =&gt; unique_slug('Post', $request-&gt;input('title')),
          'title'         =&gt; $request-&gt;input('title'),
          'description'   =&gt; $request-&gt;input('description'),
          'summary'       =&gt; $request-&gt;input('summary'),
      ]);
  
      $post-&gt;tags()-&gt;attach($tags);
  
      return redirect(route('theme.post.show', [$theme-&gt;slug, $post-&gt;slug]))-&gt;with(['success', trans('messages.post.store')]);
  }
  </code></pre>
  
  <p>The code is a little sloppy and redundant when using it in multiple controllers.  </p>
  
  <p>In order to solve this, I've created a <code>ValidationServiceProvider</code> to extend the core validator rules. Something like this:</p>
  
  <pre><code>$this-&gt;app['validator']-&gt;extend('tags', function ($attribute, $value, $parameters)
  {
      $tags = explode(',', $value);
      $tags = Tag::whereIn('title', $tags)-&gt;lists('id');
  
      if(count($tags) &lt; 1 || count($tags) &gt; 5))
      {
          return false;
      }
  });
  </code></pre>
  
  <p>Pretty neat. The thing is I still need to be able to access the <code>$tags</code> variable within the controller (because of <code>-&gt;attach($tags)</code>).</p>
  
  <p>Is there a better way of tackling this problem? Or should I stop thinking and just use (and repeat) the code I have?</p>
  
  <p>Thanks in advance, hope it makes some sence.</p>