Question: Many to many relationships store and update in laravel

Question

Many to many relationships store and update in laravel

Answers 1
Added at 2016-12-28 05:12
Tags
Question

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.

Answers to

Many to many relationships store and update in laravel

nr: #1 dodano: 2016-12-28 05:12

Try doing like this in storeTags()

$post->save();
if (isset($request->tags)) {
    $post->tags()->sync($request->tags, false);
} else {
    $post->tags()->sync(array());
}

In updateTags()

$post->save();
if (isset($request->tags)) {
    $post->tags()->sync($request->tags);
} else {
    $post->tags()->sync(array());
}

In you html file for the tags, use this

<select class="form-control select2-multi" name="tags[]" multiple="multiple">
    @foreach ($tags as $tag)
        <option value="{{ $tag->id }}">{{ $tag->name }}</option>
    @endforeach
</select>

There is a difference that in sync() method for update no need of the second parameter.
I recommend you to watch this whole playlist of tag creating

Source Show
◀ Wstecz