title: Saving image tags to a pivot table in Laravel
body: <p>Pardon my newb question, this question is mostly due to my stubborn lack of understanding of many to many relationships in Laravel.</p>
  
  <p>On my site, users can upload images</p>
  
  <pre><code>$images = new Images;
  ...
  $images-&gt;save();
  </code></pre>
  
  <p>accompanied by tags that the users create themselves. These tags are stored as an array, validated, then checked if the tag exists. If the tag exists, I want an entry on 'tagmap' that relates the new image to that tag. If it doesn't exist, I want the same thing to happen but also have a new tag be created.</p>
  
  <p>I have 3 tables, an image table, a tags table, and a pivot table called 'tagmap' which only has the columns 'image_id' and 'tag_id'.</p>
  
  <p>So after the image is saved :</p>
  
  <pre><code>$tags = new Tag;        
  foreach ($request-&gt;tags as $tags ) {
      if(preg_match('/^[a-zA-Z]+[a-zA-Z0-9._]+$/', $tags)) {
          if (strlen($tags) &lt; 21) {
              if (Tag::where('tagname', $tags)-&gt;count() &gt; 0) {
                  //store tag_id and image_id association on 'tagmap' table, no need to create new tag because tag exists
              } else {
                  //create new tag on the 'tags' table
                  //store tag_id and image_id association on 'tagmap' table
              }   
          } else {
              return redirect()-&gt;back()-&gt;with('info', 'Tags may only contain 20 characters.');    
          }   
      } else {
          return redirect()-&gt;back()-&gt;with('info', 'Tags may only contain letters and numbers, and must start with letters.'); 
      }
  }       
  $tags-&gt;save();
  </code></pre>
  
  <p>The commented out sections is where I'm having trouble.</p>
  
  <p>Here is my Tag model :</p>
  
  <pre><code>class Tag extends Model {
    protected $table = 'tags';
  
    protected $fillable = [
        'tagname',
    ];
  
    public function Images() {
        return $this-&gt;belongsToMany('CommendMe\Models\Images');
    } 
  }
  </code></pre>
  
  <p>and in my Images model I have:</p>
  
  <pre><code>class Images extends Model {
  
    protected $table = 'images';
  
    public function tags() {
         return $this-&gt;belongsToMany('CommendMe\Models\Tag');
    } 
  
  }
  </code></pre>
  
  <p>any help would be appreciated! </p>