dimanche 13 mars 2016

How To Attach the tags with the Article in Laravel 5?

I'm using Select 2 in the front end for the multiple tag selection, and I'm using Form model binding to open the Form. like this:

<div class="form-group">
{!! Form::label('tags','Tags:') !!}
{!! Form::select('tags[]', $tags,null,['id'=>'tag_list', 'class'=>'form-control','multiple']) !!}

My Js script part is:

  <script type="text/javascript">

$('#tag_list').select2({
    'placeholder':'Choose Tags',
    tags:true,
    tokenSeparators:[",", " "],
    createTag:function(newTag){
        return{
            id:'new:' + newTag.term,
            text:newTag.term + '(new)'
        };
    }
});

</script>

And in Controller I'm checking the request and creating new tags if any new tags has been input or attaching the existing selected tags from the database.

if ( ! $request->has('tags'))
        {
            $article->tags()->detach();
            return;
        }

        $alltags = array();

        foreach ($request->input('tags') as $tag)
        {
         if (substr($tag, 0, 4) == 'new:')
            {
                $newTag = Tag::create(['name' => substr($tag, 4)]);
                $alltags[] = $newTag->id;
                //dd($newTag);
                continue;
            }

        }
    $article->tags()->attach($alltags);
    $tags = DB::table('tags')->lists('name','tag_id');
    $categories=DB::table('categories')->lists('category_name','category_id');

     return view('admin.pages.edit', compact('article','tags','categories'));

Although, it does save all the new tags in the database, it doesn't attach the tags with the article. Rather it throws an exception:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`blogs`.`article_tag`, CONSTRAINT `article_tag_tag_id_foreign` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`tag_id`) ON DELETE CASCADE) (SQL: insert into `article_tag` (`post_id`, `tag_id`) values (16, ), (16, ), (16, ), (16, ))

I've three tables, one article table, another tags and yet another article_tag and using belongsToMany relationship between article and tag. I've no idea, how would I be dealing with this problem, Any thoughts would be appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire