Relationship Many to Many with select multiplo in Laravel

Asked

Viewed 308 times

1

I have the Post and Tag models with a Many to Many relationship. When registering a post the previously registered tags appear normally in select and I can save in the bank. In the edit form I am not able to make the selected and available tags appear. Either it appears the selected ones or it appears the available ones taking one foreach and leaving the other one. The way it is, appears the selected by the user but the available tags do not appear.

Post

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

protected $fillable = [
    'title', 
    'text',
    'slug',
];

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

public function photos()
{
    return $this->morphMany('App\Photo', 'photoable');
}

}

Tag

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{

protected $fillable = [
    'name', 
];

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

}

Controller

public function store(PostRequest $request)
{
    $data = $request->all();
    $this->post = new Post($data);
    $this->post->slug = str_slug($request->slug);
    $this->post->save();
    $this->post->tags()->sync($request->tag_id);

    if (!empty($this->photo = $request->file)) {
        foreach($this->photo as $photo) {
            $this->photo = new Photo();
            $this->photo->name = $photo->getClientOriginalName();
            $this->photo->photoable_id = $this->post->id;
            $this->photo->photoable_type = Post::class; 
            $path = $photo->storeAs('public', $this->photo->name);
            $this->photo->save();
        }
        Session::flash('alert-success', 'Post incluído com sucesso!');
        return redirect()->route('indexPost');
    }
    Session::flash('alert-success', 'Post incluído com sucesso!'); 
    return redirect()->route('indexPost');
}

public function edit($id)
{
    $tags = Tag::all();
    $this->post = Post::find($id);
    $photos = $this->post->photos;
    return view('post.edit')->with('post', $this->post)->with('tags', $tags)->with('photos', $photos);
}

View:

<div class="form-group">
    <label class="col-sm-2 control-label">Tag</label>
        <div class="col-sm-10">
            <select class="select2 select2-multiple" multiple="multiple" multiple name="tag_id[]">
            @foreach($tags as $tag)
                @foreach($post->tags as $tags)
                    <option {{ $tag->id == $tags->id ? 'selected' : ''}} value="{{ $tag->id }}">{{ $tag->name }}</option> 
                @endforeach
            @endforeach
            </select>
      </div>
</div>

1 answer

1


Some changes to your code:

Controller

public function edit($id)
{
    $tags = Tag::all();
    $this->post = Post::with(['photos','tags'])->find($id);
    $photos = $this->post->photos;
    if (!is_null($this->post->tags)) {
        $tagsSelected = array_map(function($a){
            return $a['id'];
        }, $this->post->tags->toArray());
    }
    else 
    {
        $tagsSelected = array();
    }
    return view('post.edit')
             ->with('tagsSelected',$tagsSelected)
             ->with('post', $this->post)
             ->with('tags', $tags)
             ->with('photos', $photos);
}

View

<div class="form-group">
    <label class="col-sm-2 control-label">Tag</label>
        <div class="col-sm-10">
            <select class="select2 select2-multiple" 
                    multiple="multiple" multiple name="tag_id[]">
            @foreach($tags as $tag)                
               <option {{ in_array($tag->id,$tagsSelected) ? 'selected' : ''}} 
                                value="{{ $tag->id }}">
                 {{ $tag->name }}
               </option>     
            @endforeach
            </select>
      </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.