I have Post and Tag models with a many to many relationship. When registering a post the previously registered tags usually appear in the select and I can save in the database. In the form of editing I am not able to make the selected and available tags appear. Either the selected ones appear or the ones available appear by taking one foreach and leaving the other one. As it is, the ones selected by the user appear 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>