cviebrock / eloquent-taggable

Easily add the ability to tag your Eloquent models in Laravel.
MIT License
537 stars 72 forks source link

Suggestion, add getTag method to Taggable trait to qucikly check if has tag #87

Closed MordiSacks closed 5 years ago

MordiSacks commented 5 years ago

This a suggestion, I would send a pull request but I'm not very familiar with unit testing my suggestion is to add this method

   /**
     * Get specific tag if is attached to this model
     *
     * @param int|string|Tag $tag
     *
     * @return Tag|null
     */
    public function getTag($tag)
    {
        $query = $this->tags();

        if ($tag instanceof Tag) {
            $tag = $tag->tag_id;
        }

        if (is_int($tag)) {
            $query->where('taggable_taggables.tag_id', $tag);
        } elseif (is_string($tag)) {
            $normalized = call_user_func(config('taggable.normalizer'), $tag);
            $query->where('normalized', $normalized);
        } else {
            return null;
        }

        return $query->get()->first();
    }

then if you want to check if the model has that tag just do like this

// by id
$model->getTag(1); // return null or Tag

// by name
$model->getTag('my tag'); // return null or Tag

// by tag instance
$model->getTag(Tag::all()->fist()); // return null or Tag

One way this could be useful

<select multiple>
    <?php foreach ($tags as $tag): ?>
        <option value="<?php echo $tag->name ?>" <?php echo $model->getTag($tag) ? 'selected' : '' ?>>
            <?php echo $tag->name ?>
        </option>
    <?php endforeach; ?>
</select>
cviebrock commented 5 years ago

I've added hasTag() to version 3.5.1, so this should work:

<select multiple>
    <?php foreach ($tags as $tag): ?>
        <option value="<?php echo $tag->name ?>" <?php echo $model->hasTag($tag) ? 'selected' : '' ?>>
            <?php echo $tag->name ?>
        </option>
    <?php endforeach; ?>
</select>