2
votes

in many to many join i get this error :

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (laravel.posts_tag, CONSTRAINT posts_tag_tag_id_foreign FOREIGN KEY (Tag_ID) REFERENCES Tag (ID) ON DELETE CASCADE) (SQL: insert into Posts_Tag (Posts_ID, Tag_ID) values (26, Tag num 2))

my controller :

public function Share(Request $request)
{

    $posts = Posts::create($request->all());

    $posts->tags()->attach(Input::get('Tag'));

    return $posts;

    return Redirect()->back();

}

my model :

public function tags()
{
    return $this->belongsToMany('App\Tag', 'Posts_Tag', 'Posts_ID', 'Tag_ID');
}

view :

            {{ Form::open(array('url'=>'post')) }}

            {{ Form::label('Title') }} : {{ Form::text('Title') }}
            <br>
            {{ Form::label('Content') }} : {{ Form::textarea('Content') }}
            <br>
            {{ Form::label('Tag :') }}
            <select name="Tag" id="Tag" class="Tag">
                @foreach($tag as $tag)
                    <option>{{ $tag->Tag }}</option>
                @endforeach
            </select>
            <br>
            {{ Form::submit('Share Post') }}

            {{ Form::close() }}
2
Please work on your caps and grammar. - user9107868

2 Answers

2
votes

Because you are not passing any tag id, fill the option's value

<select name="tags" id="Tag" class="Tag">
                //tags is a better name for collection of tgas
       @foreach($tags as $tag)
              <option value='{{$tag->id}}'>{{ $tag->Tag }}</option>
       @endforeach
</select>

And in your controller

$post->tags()->attach($request->tags);
0
votes

You can't use actual tag names with attach(). Because you're passing name instead of ID, you need to get tag ID first:

$post = Posts::create($request->all());
$tagId = Tag::where('name', $request->tag)->value('id');
$post->tags()->attach(tagId);