Wednesday, March 8, 2017

Save data and attach at same time in Laravel

i got a blog app that i need to add tags on post, i have a input field, post model, tag model and 3 tables on database: posts, tags and tag_post with ManyToMany relationship, but when i try to add new tag on table, it send to tag_post table and no tag table. i did trying change my model and controller but it worse.

Post Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

  protected $filliable = ['PostTitle', 'post', 'slug'];

  public function categories()
  {
    return $this->BelongsToMany('App\Categories', 'category_post');
  }

  public function tags()
  {
    return $this->BelongsToMany('App\Tag', 'tag_post');
  }

}

Tag Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model { protected $filliable = ['tag'];

public function posts()
{
  return $this->BelongsToMany('App\Post', 'tags_post');
}

}

PostController

  public function store(Request $request)
{

    $post = new Post;
    $post->user_id = auth::id();
    $post->PostTitle = $request->PostTitle;
    $post->post = $request->post;
    $post->slug = $request->slug;
    $post->status = '1';
    $post->save();
    $post->categories()->attach($request->categories);

    if($request->new_tags){
      foreach ($request->$new_tags as $new_tags) {
        $tag = Tag::create(['name'=> $new_tags]);
        if($tag){
          $post->tags()->attach($tags->id);
        }
      }
    }
    return redirect('blog')->with('messageSuccess', '¡Tu entrada se ha creado Exitosamente!');
}

Form

<div class="post-panel-3">
            <div class="form-group">
              <label for="postTags">Etiquetas: </label>

              <input  type="text" name="tags[]" value=" " class="form-control" placeholder="Etiquetas" id="tagBox">

            </div>



via Johanng1993

Advertisement