M
M
Mikhail A.2020-11-09 12:39:23
Laravel
Mikhail A., 2020-11-09 12:39:23

How to store multiple field with link in Laravel?

There are two models (Post and Tag). The hasMany connection from Post to Tag, feedback from Tag to Post is not needed. A post can have multiple tags.

How to store the multiple value of tags (in case the select form has the value multiple)? The single value is saved, everything is fine. But how do you keep multiple tags?

Model (Post):

public function tags()
{
    return $this->hasMany('App\Models\Tag', 'id', 'tag_id');
}

Post Controller:
public function store()
{
    ...
    $posts->tag_id = $data['tag_id'];
    ...
}

Blade (post creation form):
<select name="tag_id">
    @foreach($tags as $tag)
        <option value="{{ $tag->id }}">{{ $tag->title }}</option>
    @endforeach
</select>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pLavrenov, 2020-11-09
@pLavrenov

laravel.com (link to answer)
I always advise everyone to read at least once all the documentation in order to understand what is there and what is not there, and to navigate where to look.
In general, from the code, I realized that it is necessary not "to save tags" but to "add tags to the post", but this is also in the documentation at the same link.

J
jazzus, 2020-11-09
@jazzus

The connection is needed ManyToMany. posts can have common tags otherwise the tags don't make sense. If you plan to add tags to different models (to posts, projects, questions), then polymorphic There is a direct example with tags.
Bulk add/sync via sync method https://laravel.com/docs/8.x/eloquent-relationship...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question