mardi 27 décembre 2016

Many to many relationships store and update in laravel

I create three tables:

Post Table

id--title--body

Tags Table

id--name

post_tag

post_id--tag_id

Post Model

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

Tag Model

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

This is a many to many relation

I want to store tags when add new post and update tags when update post, and I use bootstrap-tagsinput plugin, for add post,I use this method to store the new tags:

public function storeTags($post, $tags)
{
    $tagInputArr = explode(',', $tags);
    $tagArr = [];
    foreach ($tagInputArr as $tag) {
        $tagArr[] = new Tag(['name' => $tag]);
    }
    $post->tags()->saveMany($tagArr);
}

$post is the new post object, $tags is the tag string from $request.

For update post,I have a problem,when I view the edit post page,the default tags is selected from database,If I want to add new tags the storeTags method is not work.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire