Skip to content
Advertisement

Laravel, function create and edit, retrieve data from tags

I have a basic article and tag system, with a Many to Many relationship. I manage to display all tags in the create function but I don’t know how to display all tags and tags checked in the edit function.

Article :

public function tags()
{
    return $this->belongsToMany(Tag::class)->withTimestamps();
}

Tag :

public function article()
{
    return $this->belongsToMany(Article::class)->withTimestamps();
}

function create :

public function create()
{
    $article = new Article();
    $tags = $article->tags = Tag::all();
    return view('articles.create', compact('article','tags'));
}

function edit

public function edit(Article $article)
{
    return view('articles.edit', compact('article'));
}

form

<div class="form-group">
    @foreach($article->tags as $tag)
    <label><input type="checkbox" name="tags[]" value="{{ $tag->id }}" /> {{ $tag->name }}</label>
    @endforeach
</div>

really need help pls, it’s for a school project. and sorry for my english… create: screen for add an article edit : screen for edit an article

Advertisement

Answer

here I found it ! just needed a second foreach

@foreach ($tags as $tag)
   <label><input type="checkbox" name="tags[]" value="{{ $tag->id }}"
      @foreach ($article->tags as $article_tags)
        {{ $article_tags->id == $tag->id ? 'checked' : '' }}
      @endforeach>{{ $tag->name }}</label>
@endforeach

and in the create $tags= Tag::all();

thanks for the help anyway ^^

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement