rtconner / laravel-tagging

Tag support for Laravel Eloquent models - Taggable Trait
MIT License
882 stars 168 forks source link

How to check the tags checkbox in edit article page if the article is tagged by tag x #189

Closed teikun-86 closed 4 years ago

teikun-86 commented 4 years ago

Hi, How to check the tags checkbox in edit article page if the article is tagged by tag x?

controller

`$tags = DB::table('tagging_tags')->get();

view

@foreach($tags as $tag)

<input type="checkbox" name="tags[]" value="{{$tag->slug}}"> <label>{{$tag->name}}</label>

// how to check the checkbox above if the article is tagged by tags above?

@endforeach

nickfls commented 4 years ago

@ajizusama you would want to compare the base list of tags to what is in article. something along the lines of within your view

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

@endforeach

I prefer to work with models, rather then stdClasses:

Something like this: in controller:

use Conner\Tagging\Model\Tag;

...
$tags = Tag::get();

and in view (assuming you have $article that is Taggable)

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

looks almost the same, but instead of a stdClass you have a Tag Eloquent model - and they are powerful beasts.

teikun-86 commented 4 years ago

@nickfls thanks, it's work 👍