在 Laravel 中轻松添加标记 Eloquent 模型的功能。
Easily add the ability to tag your Eloquent models in Laravel.
NOTE: These instructions are for the latest version of Laravel.
If you are using an older version, please install a version of the package that correlates to your Laravel version.
Depending on your version of Laravel, you should install a different version of the package. NOTE: As of version 6.0, the package's version should match the Laravel version.
| Laravel Version | Package Version |
|---|---|
| ^13.0 | ^13.0 |
| ^12.0 | ^12.0 |
| ^11.0 | ^11.0 |
| ^10.0 | ^10.0 |
| 9.0 | ^9.0 |
| 8.0 | ^8.0 |
| 7.0 | ^7.0 |
| 6.0 | ^6.0 |
| 5.8 | 3.5.* |
| 5.7 | 3.4.* |
| 5.6 | 3.3.* |
| 5.5 | 3.2.* |
| 5.4 | 3.1.*† |
† Version 3.1 of the package requires PHP 7.0 or later, even though Laravel 5.4 doesn't.
Older versions of Laravel can use older versions of the package, although they are no longer supported or maintained. See CHANGELOG.md and UPGRADING.md for specifics, and be sure that you are reading the correct README.md for your version (GitHub displays the version in the master branch by default, which might not be what you want).
Install the cviebrock/eloquent-taggable package via composer:
$ composer require cviebrock/eloquent-taggableThe package will automatically register its service provider.
Publish the configuration file:
php artisan vendor:publish --provider="Cviebrock\EloquentTaggable\ServiceProvider" --tag "config"Publish the migrations:
php artisan vendor:publish --provider="Cviebrock\EloquentTaggable\ServiceProvider" --tag "migrations"If you modify the migrations, keep in mind that you can add more fields, but shouldn't remove any existing ones.
Also note that if you want to change the table names used for the package, this
should be done in the configuration file (under the tables key).
Finally, use artisan to run the migration to create the required tables:
composer dump-autoload
php artisan migrate(Note that the migration file isn't published to your application, but will run anyway.)
Your models should use the Taggable trait:
use Cviebrock\EloquentTaggable\Taggable;
class MyModel extends Eloquent
{
use Taggable;
}NOTE: Make sure your model doesn't have an attribute and/or column in its database table called
tags; the trait will add that attribute for you.
That's it ... your model is now "taggable"!
Tag your models with the tag() method:
// Pass in a delimited string:
$model->tag('Apple,Banana,Cherry');
// Or an array:
$model->tag(['Apple', 'Banana', 'Cherry']);The tag() method is additive, so you can tag the model again and those tags will be added to the previous ones:
$model->tag('Apple,Banana,Cherry');
$model->tag('Durian');
// $model now has four tagsYou can remove tags individually with untag() or entirely with detag():
$model->tag('Apple,Banana,Cherry');
$model->untag('Banana');
// $model is now just tagged with "Apple" and "Cherry"
$model->detag();
// $model has no tagsYou can also completely retag a model (a short form for detagging then tagging):
$model->tag('Apple,Banana,Cherry');
$model->retag('Etrog,Fig,Grape');
// $model is now just tagged with "Etrog", "Fig", and "Grape"If you have an array of Tag model IDs (primary keys) already, you can tag a model using those IDs instead of the tag names:
// assuming no other tags exist yet ...
$model->tag('Apple','Banana','Cherry','Durian');
$newModel->tagById([1,3]);
// ... $newModel is tagged with "Apple" and "Cherry"Similarly, you can untag by ID as well:
// assuming no other tags exist yet ...
$model->tag('Apple','Banana','Cherry','Durian');
$model->untagById([1,3]);
// ... $model is now only tagged with "Banana" and "Durian"Tagging/untagging/retagging by ID is useful if you have, for instance, a form with a multi-select dropdown or a list of checkboxes of all tags, e.g.:
Apple
Banana
Cherry
... etc.
When the form submits, the data sent to your controller is an array of all the selected tag IDs. It is then easy to update the model accordingly with the selected tags:
$tags = $request->input('tags');
$model->retagById($tags);You can get the array of all tags (technically, an Eloquent Collection):
foreach($model->tags as $tag)
{
echo $tag->name;
}You can also get the list of tags as a flattened array, or a delimited list:
$model->tag('Apple,Banana,Cherry');
var_dump($model->tagList);
// string 'Apple,Banana,Cherry' (length=19)
var_dump($model->tagArray);
// array (size=3)
// 1 => string 'Apple' (length=5)
// 2 => string 'Banana' (length=6)
// 3 => string 'Cherry' (length=6)Tag names are normalized (see below) so that duplicate tags aren't accidentally created:
$model->tag('Apple');
$model->tag('apple');
$model->tag('APPLE');
var_dump($model->tagList);
// string 'Apple' (length=5)You can also see if a model has a certain tag:
$model->tag('Apple,Banana,Cherry');
// tests use the normalized tag name
var_dump($model->hasTag('apple'));
// bool(true)
var_dump($model->hasTag('Durian'));
// bool(false)For reference, imagine the following models have been tagged:
| Model Id | Tags |
|---|---|
| 1 | - no tags - |
| 2 | apple |
| 3 | apple, banana |
| 4 | apple, banana, cherry |
| 5 | cherry |
| 6 | apple, durian |
| 7 | banana, durian |
| 8 | apple, banana, durian |
You can easily find models with tags through some query scopes:
// Find models that are tagged with all the given tags
// i.e. everything tagged "Apple AND Banana".
// (returns models with Ids: 3, 4, 8)
Model::withAllTags('Apple,Banana')->get();
// Find models with any one of the given tags
// i.e. everything tagged "Apple OR Banana".
// (returns Ids: 2, 3, 4, 6, 7, 8)
Model::withAnyTags('Apple,Banana')->get();
// Find models that have any tags
// (returns Ids: 2, 3, 4, 5, 6, 7, 8)
Model::isTagged()->get();And the inverse:
…Some edge-case examples:
// Passing an empty tag list to a scope either throws an
// exception or returns nothing, depending on the
// "throwEmptyExceptions" configuration option
Model::withAllTags('');
Model::withAnyTags('');
// Returns nothing, because the "Fig" tag doesn't exist
// so no model has that tag
Model::withAllTags('Apple,Fig');Combining scopes:
…Finally, you can easily find all the tags used across all instances of a model:
// Returns an array of tag names used by all Model instances
// e.g.: ['apple','banana','cherry','durian']
Model::allTags();
// Same as above, but as a delimited list
// e.g. 'apple,banana,cherry,durian'
Model::allTagsList();
// Returns a collection of all the Tag models used by any Model instances
Model::allTagModels();You can create a listener to handle when a model is tagged:
// in your EventServiceProvider
use Cviebrock\EloquentTaggable\Events\ModelTagged;
...
protected $listen = [
...
ModelTagged::class => [
ReactModelTagged::class // your Listener class
]
...
];The listener receives the Cviebrock\EloquentTaggable\Events\ModelTagged event
with the model and tags:
namespace App\Listeners;
use Cviebrock\EloquentTaggable\Events\ModelTagged;
class ReactModelTagged
{
/**
* Handle the event.
*
* @param ModelTagged $event
* @return void
*/
public function handle(ModelTagged $event)
{
dd($event->getModel(), $event->getTags());
}
}You can use also listen for the Cviebrock\EloquentTaggable\Events\ModelUntagged event
which is fired when a tag is removed.
You can rename a tag for your model:
Model::rename('Apple', 'Apricot');This will only affect instances of Model that were tagged "Apple". If another model was also tagged
"Apple", those tags won't be renamed. (To rename a tag across all models, see the example below under
the TagService Class.)
You can also get a list of popular tags for your model (including the model count):
$tags = Model::popularTags($limit);
$tags = Model::popularTagsNormalized($limit);
// Will return an array like:
//
// [
// 'apple' => 5,
// 'banana' => 3,
// 'durian' => 3,
// 'cherry' => 2,
// ]You can also provide a minimum count (i.e., only return tags that have been used 3 or more times):
$tags = Model::popularTags($limit, 3);(Again, the above will limit the query to one particular model. To get a list of popular tag across all models, see the example below under the TagService Class.)
There are a few methods you can run on the Tag model itself.
Tag::findByName('Apple') will return the Tag model for the given name. This can
then be chained to find all the related models.
Under the hood, the above uses a byName() query scope on the Tag model, which you
are also free to use if you want to write a custom query.
You can also use TagService class directly, however almost all the functionality is
exposed via the various methods provided by the trait, so you probably don't need to.
…As always, take a look at the code for full documentation of the service class.
Configuration is handled through the settings in /app/config/taggable.php. The default values are:
return [
'delimiters' => ',;',
'glue' => ',',
'normalizer' => 'mb_strtolower',
'connection' => null,
'throwEmptyExceptions' => false,
'taggedModels' => [],
'model' => \Cviebrock\EloquentTaggable\Models\Tag::class,
'tables' => [
'taggable_tags' => 'taggable_tags',
'taggable_taggables' => 'taggable_taggables',
],
];These are the single-character strings that can delimit the list of tags passed to the tag() method.
By default, it's just the comma, but you can change it to another character, or use multiple characters.
For example, if delimiters is set to ";,/", then this will work as expected:
$model->tag(暂无开放 Issues,或尚未同步最近议题。