├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── composer.json ├── config └── config.php ├── database └── migrations │ ├── 2020_01_01_000001_create_tags_table.php │ └── 2020_01_01_000002_create_taggables_table.php ├── phpstan.neon.dist └── src ├── Console └── Commands │ ├── MigrateCommand.php │ ├── PublishCommand.php │ └── RollbackCommand.php ├── Models └── Tag.php ├── Providers └── TagsServiceProvider.php └── Traits └── Taggable.php /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Rinvex Tags Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | This project adheres to [Semantic Versioning](CONTRIBUTING.md). 6 | 7 | 8 | ## [v7.1.2] - 2023-07-03 9 | - Update composer dependencies 10 | - Use canonicalized absolute pathnames for resources 11 | 12 | ## [v7.1.1] - 2023-06-29 13 | - Refactor resource loading and publishing 14 | 15 | ## [v7.1.0] - 2023-05-02 16 | - 92c9893: Add support for Laravel v11, and drop support for Laravel v9 17 | - fe5e1cc: Upgrade spatie/laravel-translatable to v6.5 from v6.0 18 | - 0aa8804: Upgrade spatie/laravel-sluggable to v3.4 from v3.3 19 | - 510cf86: Update phpunit to v10.1 from v9.5 20 | 21 | ## [v7.0.0] - 2023-01-09 22 | - Add Relation::morphMap 23 | - Tweak artisan commands registration 24 | - Drop PHP v8.0 support and update composer dependencies 25 | - Utilize PHP 8.1 attributes feature for artisan commands 26 | 27 | ## [v6.1.2] - 2022-08-30 28 | - Update exists and unique validation rules to use models instead of tables 29 | 30 | ## [v6.1.1] - 2022-06-20 31 | - Update composer dependencies spatie/laravel-translatable to ^6.0.0 from ^5.2.0 32 | 33 | ## [v6.1.0] - 2022-02-14 34 | - Update composer dependencies to Laravel v9 35 | - Add support for model HasFactory 36 | - Check before detaching tags if deleted entity was soft deleted 37 | 38 | ## [v6.0.0] - 2021-08-22 39 | - Drop PHP v7 support, and upgrade rinvex package dependencies to next major version 40 | - Update composer dependencies 41 | 42 | ## [v5.0.5] - 2021-05-24 43 | - Merge rules instead of resetting, to allow adequate model override 44 | - Update spatie/eloquent-sortable composer package to v4.0.0 45 | - Update spatie/laravel-translatable composer package to v5.0.0 46 | - Update spatie/laravel-sluggable composer package to v3.0.0 47 | 48 | ## [v5.0.4] - 2021-05-11 49 | - Fix constructor initialization order (fill attributes should come next after merging fillables & rules) 50 | 51 | ## [v5.0.3] - 2021-05-07 52 | - Drop old MySQL versions support that doesn't support json columns 53 | - Upgrade to GitHub-native Dependabot 54 | - Utilize SoftDeletes 55 | 56 | ## [v5.0.2] - 2021-02-06 57 | - Simplify service provider model registration into IoC 58 | - Update phpdoc to match method signature 59 | - Enable StyleCI risky mode 60 | 61 | ## [v5.0.1] - 2020-12-25 62 | - Add support for PHP v8 63 | 64 | ## [v5.0.0] - 2020-12-22 65 | - Upgrade to Laravel v8 66 | - Move custom eloquent model events to module layer from core package layer 67 | - Refactor and tweak Eloquent Events 68 | 69 | ## [v4.1.1] - 2020-07-16 70 | - Update validation rules 71 | 72 | ## [v4.1.0] - 2020-06-15 73 | - Update validation rules 74 | - Drop using rinvex/laravel-cacheable from core packages for more flexibility 75 | - Caching should be handled on the application layer, not enforced from the core packages 76 | - Drop PHP 7.2 & 7.3 support from travis 77 | - Drop slugifying group attribute 78 | 79 | ## [v4.0.6] - 2020-05-30 80 | - Remove default indent size config 81 | - Add strip_tags validation rule to string fields 82 | - Specify events queue 83 | - Explicitly specify relationship attributes 84 | - Add strip_tags validation rule 85 | - Explicitly define relationship name 86 | 87 | ## [v4.0.5] - 2020-04-12 88 | - Fix ServiceProvider registerCommands method compatibility 89 | 90 | ## [v4.0.4] - 2020-04-09 91 | - Tweak artisan command registration 92 | - Reverse commit "Convert database int fields into bigInteger" 93 | - Refactor publish command and allow multiple resource values 94 | 95 | ## [v4.0.3] - 2020-04-04 96 | - Fix namespace issue 97 | 98 | ## [v4.0.2] - 2020-04-04 99 | - Enforce consistent artisan command tag namespacing 100 | - Enforce consistent package namespace 101 | - Drop laravel/helpers usage as it's no longer used 102 | 103 | ## [v4.0.1] - 2020-03-20 104 | - Convert into bigInteger database fields 105 | - Add shortcut -f (force) for artisan publish commands 106 | - Fix migrations path 107 | 108 | ## [v4.0.0] - 2020-03-15 109 | - Upgrade to Laravel v7.1.x & PHP v7.4.x 110 | 111 | ## [v3.0.4] - 2020-03-13 112 | - Tweak TravisCI config 113 | - Add migrations autoload option to the package 114 | - Tweak service provider `publishesResources` 115 | - Remove indirect composer dependency 116 | - Drop using global helpers 117 | - Update StyleCI config 118 | 119 | ## [v3.0.3] - 2019-12-18 120 | - Fix `migrate:reset` args as it doesn't accept --step 121 | - Create event classes and map them in the model 122 | 123 | ## [v3.0.1] - 2019-09-24 124 | - Add missing laravel/helpers composer package 125 | 126 | ## [v3.0.0] - 2019-09-23 127 | - Upgrade to Laravel v6 and update dependencies 128 | 129 | ## [v2.1.1] - 2019-06-03 130 | - Enforce latest composer package versions 131 | 132 | ## [v2.1.0] - 2019-06-02 133 | - Update composer deps 134 | - Drop PHP 7.1 travis test 135 | - Refactor migrations and artisan commands, and tweak service provider publishes functionality 136 | 137 | ## [v2.0.0] - 2019-03-03 138 | - Rename environment variable QUEUE_DRIVER to QUEUE_CONNECTION 139 | - Require PHP 7.2 & Laravel 5.8 140 | - Apply PHPUnit 8 updates 141 | 142 | ## [v1.0.1] - 2018-12-22 143 | - Update composer dependencies 144 | - Add PHP 7.3 support to travis 145 | - Fix MySQL / PostgreSQL json column compatibility 146 | 147 | ## [v1.0.0] - 2018-10-01 148 | - Enforce Consistency 149 | - Support Laravel 5.7+ 150 | - Rename package to rinvex/laravel-tags 151 | 152 | ## [v0.0.5] - 2018-09-21 153 | - Update travis php versions 154 | - Fix wrong function names 155 | - Drop StyleCI multi-language support (paid feature now!) 156 | - Update composer dependencies 157 | - Prepare and tweak testing configuration 158 | - Highlight variables in strings explicitly 159 | - Update PHPUnit options 160 | - Add tag model factory 161 | 162 | ## [v0.0.4] - 2018-02-18 163 | - Add PublishCommand to artisan 164 | - Update supplementary files 165 | - Move slug auto generation to the custom HasSlug trait 166 | - Add Rollback Console Command 167 | - Add missing composer dependencies 168 | - Add PHPUnitPrettyResultPrinter 169 | - Remove useless scopes 170 | - Refactor taggable trait for more simple and clean code 171 | - Update composer dependencies 172 | - Typehint method returns 173 | - Drop useless model contracts (models already swappable through IoC) 174 | - Add Laravel v5.6 support 175 | - Simplify IoC binding 176 | - Refactor parseTags 177 | - Fix wrong parameter names 178 | - Add force option to artisan commands 179 | - Drop Laravel 5.5 support 180 | 181 | ## [v0.0.3] - 2017-09-09 182 | - Fix many issues and apply many enhancements 183 | - Rename package rinvex/laravel-tags from rinvex/taggable 184 | 185 | ## [v0.0.2] - 2017-06-29 186 | - Enforce consistency 187 | - Update validation rules 188 | - Add Laravel 5.5 support 189 | - Fix detaching tags method 190 | - Fix multiple bugs & issues 191 | - Change integer column length 192 | - Tweak model event registration 193 | - Rename tags type to tags group 194 | - Enforce more secure approach using model fillable instead of guarded 195 | 196 | ## v0.0.1 - 2017-04-08 197 | - Rename package to "rinvex/taggable" from "rinvex/tag" based on 3b6a727 198 | 199 | [v7.1.2]: https://github.com/rinvex/laravel-tags/compare/v7.1.1...v7.1.2 200 | [v7.1.1]: https://github.com/rinvex/laravel-tags/compare/v7.1.0...v7.1.1 201 | [v7.1.0]: https://github.com/rinvex/laravel-tags/compare/v7.0.0...v7.1.0 202 | [v7.0.0]: https://github.com/rinvex/laravel-tags/compare/v6.1.2...v7.0.0 203 | [v6.1.2]: https://github.com/rinvex/laravel-tags/compare/v6.1.1...v6.1.2 204 | [v6.1.1]: https://github.com/rinvex/laravel-tags/compare/v6.1.0...v6.1.1 205 | [v6.1.0]: https://github.com/rinvex/laravel-tags/compare/v6.0.0...v6.1.0 206 | [v6.0.0]: https://github.com/rinvex/laravel-tags/compare/v5.0.5...v6.0.0 207 | [v5.0.5]: https://github.com/rinvex/laravel-tags/compare/v5.0.4...v5.0.5 208 | [v5.0.4]: https://github.com/rinvex/laravel-tags/compare/v5.0.3...v5.0.4 209 | [v5.0.3]: https://github.com/rinvex/laravel-tags/compare/v5.0.2...v5.0.3 210 | [v5.0.2]: https://github.com/rinvex/laravel-tags/compare/v5.0.1...v5.0.2 211 | [v5.0.1]: https://github.com/rinvex/laravel-tags/compare/v5.0.0...v5.0.1 212 | [v5.0.0]: https://github.com/rinvex/laravel-tags/compare/v4.1.1...v5.0.0 213 | [v4.1.1]: https://github.com/rinvex/laravel-tags/compare/v4.1.0...v4.1.1 214 | [v4.1.0]: https://github.com/rinvex/laravel-tags/compare/v4.0.6...v4.1.0 215 | [v4.0.6]: https://github.com/rinvex/laravel-tags/compare/v4.0.5...v4.0.6 216 | [v4.0.5]: https://github.com/rinvex/laravel-tags/compare/v4.0.4...v4.0.5 217 | [v4.0.4]: https://github.com/rinvex/laravel-tags/compare/v4.0.3...v4.0.4 218 | [v4.0.3]: https://github.com/rinvex/laravel-tags/compare/v4.0.2...v4.0.3 219 | [v4.0.2]: https://github.com/rinvex/laravel-tags/compare/v4.0.1...v4.0.2 220 | [v4.0.1]: https://github.com/rinvex/laravel-tags/compare/v4.0.0...v4.0.1 221 | [v4.0.0]: https://github.com/rinvex/laravel-tags/compare/v3.0.4...v4.0.0 222 | [v3.0.4]: https://github.com/rinvex/laravel-tags/compare/v3.0.3...v3.0.4 223 | [v3.0.3]: https://github.com/rinvex/laravel-tags/compare/v3.0.2...v3.0.3 224 | [v3.0.2]: https://github.com/rinvex/laravel-tags/compare/v3.0.1...v3.0.2 225 | [v3.0.1]: https://github.com/rinvex/laravel-tags/compare/v3.0.0...v3.0.1 226 | [v3.0.0]: https://github.com/rinvex/laravel-tags/compare/v2.1.1...v3.0.0 227 | [v2.1.1]: https://github.com/rinvex/laravel-tags/compare/v2.1.0...v2.1.1 228 | [v2.1.0]: https://github.com/rinvex/laravel-tags/compare/v2.0.0...v2.1.0 229 | [v2.0.0]: https://github.com/rinvex/laravel-tags/compare/v1.0.1...v2.0.0 230 | [v1.0.1]: https://github.com/rinvex/laravel-tags/compare/v1.0.0...v1.0.1 231 | [v1.0.0]: https://github.com/rinvex/laravel-tags/compare/v0.0.5...v1.0.0 232 | [v0.0.5]: https://github.com/rinvex/laravel-tags/compare/v0.0.4...v0.0.5 233 | [v0.0.4]: https://github.com/rinvex/laravel-tags/compare/v0.0.3...v0.0.4 234 | [v0.0.3]: https://github.com/rinvex/laravel-tags/compare/v0.0.2...v0.0.3 235 | [v0.0.2]: https://github.com/rinvex/laravel-tags/compare/v0.0.1...v0.0.2 236 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [help@rinvex.com](mailto:help@rinvex.com). All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guide 2 | 3 | This project adheres to the following standards and practices. 4 | 5 | 6 | ## Versioning 7 | 8 | This project is versioned under the [Semantic Versioning](http://semver.org/) guidelines as much as possible. 9 | 10 | Releases will be numbered with the following format: 11 | 12 | - `..` 13 | - `..` 14 | 15 | And constructed with the following guidelines: 16 | 17 | - Breaking backward compatibility bumps the major and resets the minor and patch. 18 | - New additions without breaking backward compatibility bump the minor and reset the patch. 19 | - Bug fixes and misc changes bump the patch. 20 | 21 | 22 | ## Pull Requests 23 | 24 | The pull request process differs for new features and bugs. 25 | 26 | Pull requests for bugs may be sent without creating any proposal issue. If you believe that you know of a solution for a bug that has been filed, please leave a comment detailing your proposed fix or create a pull request with the fix mentioning that issue id. 27 | 28 | 29 | ## Coding Standards 30 | 31 | This project follows the FIG PHP Standards Recommendations compliant with the [PSR-1: Basic Coding Standard](http://www.php-fig.org/psr/psr-1/), [PSR-2: Coding Style Guide](http://www.php-fig.org/psr/psr-2/) and [PSR-4: Autoloader](http://www.php-fig.org/psr/psr-4/) to ensure a high level of interoperability between shared PHP code. If you notice any compliance oversights, please send a patch via pull request. 32 | 33 | 34 | ## Feature Requests 35 | 36 | If you have a proposal or a feature request, you may create an issue with `[Proposal]` in the title. 37 | 38 | The proposal should also describe the new feature, as well as implementation ideas. The proposal will then be reviewed and either approved or denied. Once a proposal is approved, a pull request may be created implementing the new feature. 39 | 40 | 41 | ## Git Flow 42 | 43 | This project follows [Git-Flow](http://nvie.com/posts/a-successful-git-branching-model/), and as such has `master` (latest stable releases), `develop` (latest WIP development) and X.Y support branches (when there's multiple major versions). 44 | 45 | Accordingly all pull requests MUST be sent to the `develop` branch. 46 | 47 | > **Note:** Pull requests which do not follow these guidelines will be closed without any further notice. 48 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016-2021, Rinvex LLC, 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rinvex Tags 2 | 3 | **Rinvex Tags** is a polymorphic Laravel package, for tag management. You can tag any eloquent model with ease, and utilize the awesomeness of **[Sluggable](https://github.com/spatie/laravel-sluggable)**, and **[Translatable](https://github.com/spatie/laravel-translatable)** models out of the box. 4 | 5 | [![Packagist](https://img.shields.io/packagist/v/rinvex/laravel-tags.svg?label=Packagist&style=flat-square)](https://packagist.org/packages/rinvex/laravel-tags) 6 | [![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/rinvex/laravel-tags.svg?label=Scrutinizer&style=flat-square)](https://scrutinizer-ci.com/g/rinvex/laravel-tags/) 7 | [![Travis](https://img.shields.io/travis/rinvex/laravel-tags.svg?label=TravisCI&style=flat-square)](https://travis-ci.org/rinvex/laravel-tags) 8 | [![StyleCI](https://styleci.io/repos/87597843/shield)](https://styleci.io/repos/87597843) 9 | [![License](https://img.shields.io/packagist/l/rinvex/laravel-tags.svg?label=License&style=flat-square)](https://github.com/rinvex/laravel-tags/blob/develop/LICENSE) 10 | 11 | 12 | ## Installation 13 | 14 | 1. Install the package via composer: 15 | ```shell 16 | composer require rinvex/laravel-tags 17 | ``` 18 | 19 | 2. Publish resources (migrations and config files): 20 | ```shell 21 | php artisan rinvex:publish:tags 22 | ``` 23 | 24 | 3. Execute migrations via the following command: 25 | ```shell 26 | php artisan rinvex:migrate:tags 27 | ``` 28 | 29 | 4. Done! 30 | 31 | 32 | ## Usage 33 | 34 | To add tags support to your eloquent models simply use `\Rinvex\Tags\Traits\Taggable` trait. 35 | 36 | ### Manage your tags 37 | 38 | Your tags are just normal [eloquent](https://laravel.com/docs/master/eloquent) models, so you can deal with it like so. There's few more methods added to tag models for your convenience, let's take a look: 39 | 40 | ```php 41 | // Create new tag by name 42 | app('rinvex.tags.tag')->createByName('My New Tag'); 43 | 44 | // Create new tag by name, group, and translation 45 | app('rinvex.tags.tag')->createByName('The very new tag', 'blog', 'en'); 46 | 47 | // Find first tag by name 48 | app('rinvex.tags.tag')->firstByName('My New Tag'); 49 | 50 | // Find first tag by name, group, and translation 51 | app('rinvex.tags.tag')->firstByName('وسم جديد', 'board', 'ar'); 52 | 53 | // Find tag(s) by name 54 | app('rinvex.tags.tag')->findByName('My New Tag'); 55 | 56 | // Find tag(s) by name, group, and translation 57 | app('rinvex.tags.tag')->findByName('وسم جديد', 'board', 'ar'); 58 | 59 | // Find multiple tags by names array 60 | app('rinvex.tags.tag')->findByName(['Tag One', 'Tag Two']); 61 | 62 | // Find multiple tags by delimited names (tag delimiter is customizable) 63 | app('rinvex.tags.tag')->findByName('First Tag, Second Tag, Third Tag'); 64 | 65 | // Find tag(s) by name or create if not exists 66 | app('rinvex.tags.tag')->findByNameOrCreate('My Brand New Tag'); 67 | 68 | // Find tag(s) by name, group, and translation or create if not exists 69 | app('rinvex.tags.tag')->findByNameOrCreate(['My Brand New Tag 2', 'My Brand New Tag 3']); 70 | ``` 71 | 72 | > **Notes:** 73 | > - **Rinvex Tags** extends and utilizes other awesome packages, to be translatable out of the box using [`spatie/laravel-translatable`](https://github.com/spatie/laravel-translatable), and for automatic Slugging it uses [`spatie/laravel-sluggable`](https://github.com/spatie/laravel-sluggable) packages. Them them out. 74 | > - Both `findByName()` and `findByNameOrCreate()` methods accepts either one or more tags as their first argument, and always return a collection. 75 | 76 | ### Manage your taggable model 77 | 78 | The API is intutive and very straightforward, so let's give it a quick look: 79 | 80 | ```php 81 | // Get instance of your model 82 | $post = new \App\Models\Post::find(1); 83 | 84 | // Get attached tags collection 85 | $post->tags; 86 | 87 | // Get attached tags query builder 88 | $post->tags(); 89 | ``` 90 | 91 | You can attach tags in various ways: 92 | 93 | ```php 94 | // Single tag id 95 | $post->attachTags(1); 96 | 97 | // Multiple tag IDs array 98 | $post->attachTags([1, 2, 5]); 99 | 100 | // Multiple tag IDs collection 101 | $post->attachTags(collect([1, 2, 5])); 102 | 103 | // Single tag model instance 104 | $tagInstance = app('rinvex.tags.tag')->first(); 105 | $post->attachTags($tagInstance); 106 | 107 | // Single tag name (created if not exists) 108 | $post->attachTags('A very new tag'); 109 | 110 | // Multiple delimited tag names (use existing, create not existing) 111 | $post->attachTags('First Tag, Second Tag, Third Tag'); 112 | 113 | // Multiple tag names array (use existing, create not existing) 114 | $post->attachTags(['First Tag', 'Second Tag']); 115 | 116 | // Multiple tag names collection (use existing, create not existing) 117 | $post->attachTags(collect(['First Tag', 'Second Tag'])); 118 | 119 | // Multiple tag model instances 120 | $tagInstances = app('rinvex.tags.tag')->whereIn('id', [1, 2, 5])->get(); 121 | $post->attachTags($tagInstances); 122 | ``` 123 | 124 | > **Notes:** 125 | > - The `attachTags()` method attach the given tags to the model without touching the currently attached tags, while there's the `syncTags()` method that can detach any records that's not in the given items, this method takes a second optional boolean parameter that's set detaching flag to `true` or `false`. 126 | > - To detach model tags you can use the `detachTags()` method, which uses **exactly** the same signature as the `attachTags()` method, with additional feature of detaching all currently attached tags by passing null or nothing to that method as follows: `$post->detachTags();`. 127 | > - You may have multiple tags with the same name and the same locale, in such case the first record found is used by default. This is intended by design to ensure a consistent behavior across all functionality whether you are attaching, detaching, or scoping model tags. 128 | 129 | And as you may have expected, you can check if tags attached: 130 | 131 | ```php 132 | // Single tag id 133 | $post->hasAnyTags(1); 134 | 135 | // Multiple tag IDs array 136 | $post->hasAnyTags([1, 2, 5]); 137 | 138 | // Multiple tag IDs collection 139 | $post->hasAnyTags(collect([1, 2, 5])); 140 | 141 | // Single tag model instance 142 | $tagInstance = app('rinvex.tags.tag')->first(); 143 | $post->hasAnyTags($tagInstance); 144 | 145 | // Single tag name 146 | $post->hasAnyTags('A very new tag'); 147 | 148 | // Multiple delimited tag names 149 | $post->hasAnyTags('First Tag, Second Tag, Third Tag'); 150 | 151 | // Multiple tag names array 152 | $post->hasAnyTags(['First Tag', 'Second Tag']); 153 | 154 | // Multiple tag names collection 155 | $post->hasAnyTags(collect(['First Tag', 'Second Tag'])); 156 | 157 | // Multiple tag model instances 158 | $tagInstances = app('rinvex.tags.tag')->whereIn('id', [1, 2, 5])->get(); 159 | $post->hasAnyTags($tagInstances); 160 | ``` 161 | 162 | > **Notes:** 163 | > - The `hasAnyTags()` method check if **ANY** of the given tags are attached to the model. It returns boolean `true` or `false` as a result. 164 | > - Similarly the `hasAllTags()` method uses **exactly** the same signature as the `hasAnyTags()` method, but it behaves differently and performs a strict comparison to check if **ALL** of the given tags are attached. 165 | 166 | ### Advanced usage 167 | 168 | #### Generate tag slugs 169 | 170 | **Rinvex Tags** auto generates slugs and auto detect and insert default translation for you if not provided, but you still can pass it explicitly through normal eloquent `create` method, as follows: 171 | 172 | ```php 173 | app('rinvex.tags.tag')->create(['name' => ['en' => 'My New Tag'], 'slug' => 'custom-tag-slug']); 174 | ``` 175 | 176 | > **Note:** Check **[Sluggable](https://github.com/spatie/laravel-sluggable)** package for further details. 177 | 178 | #### Smart parameter detection 179 | 180 | **Rinvex Tags** methods that accept list of tags are smart enough to handle almost all kinds of inputs as you've seen in the above examples. It will check input type and behave accordingly. 181 | 182 | #### Retrieve all models attached to the tag 183 | 184 | You may encounter a situation where you need to get all models attached to certain tag, you do so with ease as follows: 185 | 186 | ```php 187 | $tag = app('rinvex.tags.tag')->find(1); 188 | $tag->entries(\App\Models\Post::class)->get(); 189 | ``` 190 | 191 | #### Query scopes 192 | 193 | Yes, **Rinvex Tags** shipped with few awesome query scopes for your convenience, usage example: 194 | 195 | ```php 196 | // Single tag id 197 | $post->withAnyTags(1)->get(); 198 | 199 | // Multiple tag IDs array 200 | $post->withAnyTags([1, 2, 5])->get(); 201 | 202 | // Multiple tag IDs collection 203 | $post->withAnyTags(collect([1, 2, 5]))->get(); 204 | 205 | // Single tag model instance 206 | $tagInstance = app('rinvex.tags.tag')->first(); 207 | $post->withAnyTags($tagInstance)->get(); 208 | 209 | // Single tag name 210 | $post->withAnyTags('A very new tag')->get(); 211 | 212 | // Multiple delimited tag names 213 | $post->withAnyTags('First Tag, Second Tag, Third Tag'); 214 | 215 | // Multiple tag names array 216 | $post->withAnyTags(['First Tag', 'Second Tag'])->get(); 217 | 218 | // Multiple tag names collection 219 | $post->withAnyTags(collect(['First Tag', 'Second Tag']))->get(); 220 | 221 | // Multiple tag model instances 222 | $tagInstances = app('rinvex.tags.tag')->whereIn('id', [1, 2, 5])->get(); 223 | $post->withAnyTags($tagInstances)->get(); 224 | ``` 225 | 226 | > **Notes:** 227 | > - The `withAnyTags()` scope finds posts with **ANY** attached tags of the given. It returns normally a query builder, so you can chain it or call `get()` method for example to execute and get results. 228 | > - Similarly there's few other scopes like `withAllTags()` that finds posts with **ALL** attached tags of the given, `withoutTags()` which finds posts without **ANY** attached tags of the given, and lastly `withoutAnyTags()` which find posts without **ANY** attached tags at all. All scopes are created equal, with same signature, and returns query builder. 229 | 230 | #### Tag translations 231 | 232 | Manage tag translations with ease as follows: 233 | 234 | ```php 235 | $tag = app('rinvex.tags.tag')->find(1); 236 | 237 | // Update name translations 238 | $tag->setTranslation('name', 'en', 'New English Tag Name')->save(); 239 | 240 | // Alternatively you can use default eloquent update 241 | $tag->update([ 242 | 'name' => [ 243 | 'en' => 'New Tag', 244 | 'ar' => 'وسم جديد', 245 | ], 246 | ]); 247 | 248 | // Get single tag translation 249 | $tag->getTranslation('name', 'en'); 250 | 251 | // Get all tag translations 252 | $tag->getTranslations('name'); 253 | 254 | // Get tag name in default locale 255 | $tag->name; 256 | ``` 257 | 258 | > **Note:** Check **[Translatable](https://github.com/spatie/laravel-translatable)** package for further details. 259 | 260 | 261 | ## Changelog 262 | 263 | Refer to the [Changelog](CHANGELOG.md) for a full history of the project. 264 | 265 | 266 | ## Support 267 | 268 | The following support channels are available at your fingertips: 269 | 270 | - [Chat on Slack](https://bit.ly/rinvex-slack) 271 | - [Help on Email](mailto:help@rinvex.com) 272 | - [Follow on Twitter](https://twitter.com/rinvex) 273 | 274 | 275 | ## Contributing & Protocols 276 | 277 | Thank you for considering contributing to this project! The contribution guide can be found in [CONTRIBUTING.md](CONTRIBUTING.md). 278 | 279 | Bug reports, feature requests, and pull requests are very welcome. 280 | 281 | - [Versioning](CONTRIBUTING.md#versioning) 282 | - [Pull Requests](CONTRIBUTING.md#pull-requests) 283 | - [Coding Standards](CONTRIBUTING.md#coding-standards) 284 | - [Feature Requests](CONTRIBUTING.md#feature-requests) 285 | - [Git Flow](CONTRIBUTING.md#git-flow) 286 | 287 | 288 | ## Security Vulnerabilities 289 | 290 | If you discover a security vulnerability within this project, please send an e-mail to [help@rinvex.com](help@rinvex.com). All security vulnerabilities will be promptly addressed. 291 | 292 | 293 | ## About Rinvex 294 | 295 | Rinvex is a software solutions startup, specialized in integrated enterprise solutions for SMEs established in Alexandria, Egypt since June 2016. We believe that our drive The Value, The Reach, and The Impact is what differentiates us and unleash the endless possibilities of our philosophy through the power of software. We like to call it Innovation At The Speed Of Life. That’s how we do our share of advancing humanity. 296 | 297 | 298 | ## License 299 | 300 | This software is released under [The MIT License (MIT)](LICENSE). 301 | 302 | (c) 2016-2022 Rinvex LLC, Some rights reserved. 303 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rinvex/laravel-tags", 3 | "description": "Rinvex Tags is a polymorphic Laravel package, for tag management. You can tag any eloquent model with ease, and utilize the awesomeness of Sluggable, and Translatable models out of the box.", 4 | "type": "library", 5 | "keywords": [ 6 | "tag", 7 | "model", 8 | "laravel", 9 | "taggable", 10 | "taxonomy", 11 | "eloquent", 12 | "laravel", 13 | "translatable", 14 | "polymorphic", 15 | "sluggable", 16 | "sortable", 17 | "rinvex" 18 | ], 19 | "license": "MIT", 20 | "homepage": "https://rinvex.com", 21 | "support": { 22 | "email": "help@rinvex.com", 23 | "issues": "https://github.com/rinvex/laravel-tags/issues", 24 | "source": "https://github.com/rinvex/laravel-tags", 25 | "docs": "https://github.com/rinvex/laravel-tags/blob/master/README.md" 26 | }, 27 | "authors": [ 28 | { 29 | "name": "Rinvex LLC", 30 | "homepage": "https://rinvex.com", 31 | "email": "help@rinvex.com" 32 | }, 33 | { 34 | "name": "Abdelrahman Omran", 35 | "homepage": "https://omranic.com", 36 | "email": "me@omranic.com", 37 | "role": "Project Lead" 38 | }, 39 | { 40 | "name": "The Generous Laravel Community", 41 | "homepage": "https://github.com/rinvex/laravel-tags/contributors" 42 | } 43 | ], 44 | "require": { 45 | "php": "^8.1.0", 46 | "illuminate/console": "^10.0.0 || ^11.0.0", 47 | "illuminate/database": "^10.0.0 || ^11.0.0", 48 | "illuminate/support": "^10.0.0 || ^11.0.0", 49 | "rinvex/laravel-support": "^7.0.0", 50 | "spatie/eloquent-sortable": "^4.0.0", 51 | "spatie/laravel-sluggable": "^3.4.0", 52 | "symfony/console": "^6.2.0" 53 | }, 54 | "require-dev": { 55 | "codedungeon/phpunit-result-printer": "^0.32.0", 56 | "illuminate/container": "^10.0.0 || ^11.0.0", 57 | "phpunit/phpunit": "^10.1.0" 58 | }, 59 | "autoload": { 60 | "psr-4": { 61 | "Rinvex\\Tags\\": "src/" 62 | } 63 | }, 64 | "autoload-dev": { 65 | "psr-4": { 66 | "Rinvex\\Tags\\Tests\\": "tests" 67 | } 68 | }, 69 | "scripts": { 70 | "test": "vendor/bin/phpunit" 71 | }, 72 | "config": { 73 | "sort-packages": true, 74 | "preferred-install": "dist", 75 | "optimize-autoloader": true 76 | }, 77 | "extra": { 78 | "laravel": { 79 | "providers": [ 80 | "Rinvex\\Tags\\Providers\\TagsServiceProvider" 81 | ] 82 | } 83 | }, 84 | "minimum-stability": "dev", 85 | "prefer-stable": true 86 | } 87 | -------------------------------------------------------------------------------- /config/config.php: -------------------------------------------------------------------------------- 1 | true, 9 | 10 | // Tags Database Tables 11 | 'tables' => [ 12 | 13 | 'tags' => 'tags', 14 | 'taggables' => 'taggables', 15 | 16 | ], 17 | 18 | // Tags Models 19 | 'models' => [ 20 | 'tag' => \Rinvex\Tags\Models\Tag::class, 21 | ], 22 | 23 | ]; 24 | -------------------------------------------------------------------------------- /database/migrations/2020_01_01_000001_create_tags_table.php: -------------------------------------------------------------------------------- 1 | increments('id'); 21 | $table->string('slug'); 22 | $table->json('name'); 23 | $table->json('description')->nullable(); 24 | $table->mediumInteger('sort_order')->unsigned()->default(0); 25 | $table->string('group')->nullable(); 26 | $table->timestamps(); 27 | $table->softDeletes(); 28 | 29 | // Indexes 30 | $table->unique('slug'); 31 | }); 32 | } 33 | 34 | /** 35 | * Reverse the migrations. 36 | * 37 | * @return void 38 | */ 39 | public function down(): void 40 | { 41 | Schema::dropIfExists(config('rinvex.tags.tables.tags')); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /database/migrations/2020_01_01_000002_create_taggables_table.php: -------------------------------------------------------------------------------- 1 | integer('tag_id')->unsigned(); 21 | $table->morphs('taggable'); 22 | $table->timestamps(); 23 | 24 | // Indexes 25 | $table->unique(['tag_id', 'taggable_id', 'taggable_type'], 'taggables_ids_type_unique'); 26 | $table->foreign('tag_id')->references('id')->on(config('rinvex.tags.tables.tags')) 27 | ->onDelete('cascade')->onUpdate('cascade'); 28 | }); 29 | } 30 | 31 | /** 32 | * Reverse the migrations. 33 | * 34 | * @return void 35 | */ 36 | public function down(): void 37 | { 38 | Schema::dropIfExists(config('rinvex.tags.tables.taggables')); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /phpstan.neon.dist: -------------------------------------------------------------------------------- 1 | includes: 2 | - ./vendor/nunomaduro/larastan/extension.neon 3 | parameters: 4 | level: 5 5 | paths: 6 | - src 7 | -------------------------------------------------------------------------------- /src/Console/Commands/MigrateCommand.php: -------------------------------------------------------------------------------- 1 | alert($this->description); 35 | 36 | $path = config('rinvex.tags.autoload_migrations') ? 37 | 'vendor/rinvex/laravel-tags/database/migrations' : 38 | 'database/migrations/rinvex/laravel-tags'; 39 | 40 | if (file_exists($path)) { 41 | $this->call('migrate', [ 42 | '--step' => true, 43 | '--path' => $path, 44 | '--force' => $this->option('force'), 45 | ]); 46 | } else { 47 | $this->warn('No migrations found! Consider publish them first: php artisan rinvex:publish:tags'); 48 | } 49 | 50 | $this->line(''); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Console/Commands/PublishCommand.php: -------------------------------------------------------------------------------- 1 | alert($this->description); 35 | 36 | collect($this->option('resource') ?: ['config', 'migrations'])->each(function ($resource) { 37 | $this->call('vendor:publish', ['--tag' => "rinvex/tags::{$resource}", '--force' => $this->option('force')]); 38 | }); 39 | 40 | $this->line(''); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Console/Commands/RollbackCommand.php: -------------------------------------------------------------------------------- 1 | alert($this->description); 35 | 36 | $path = config('rinvex.tags.autoload_migrations') ? 37 | 'vendor/rinvex/laravel-tags/database/migrations' : 38 | 'database/migrations/rinvex/laravel-tags'; 39 | 40 | if (file_exists($path)) { 41 | $this->call('migrate:reset', [ 42 | '--path' => $path, 43 | '--force' => $this->option('force'), 44 | ]); 45 | } else { 46 | $this->warn('No migrations found! Consider publish them first: php artisan rinvex:publish:tags'); 47 | } 48 | 49 | $this->line(''); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Models/Tag.php: -------------------------------------------------------------------------------- 1 | 'string', 72 | 'sort_order' => 'integer', 73 | 'group' => 'string', 74 | 'deleted_at' => 'datetime', 75 | ]; 76 | 77 | /** 78 | * {@inheritdoc} 79 | */ 80 | protected $observables = [ 81 | 'validating', 82 | 'validated', 83 | ]; 84 | 85 | /** 86 | * The attributes that are translatable. 87 | * 88 | * @var array 89 | */ 90 | public $translatable = [ 91 | 'name', 92 | 'description', 93 | ]; 94 | 95 | /** 96 | * The sortable settings. 97 | * 98 | * @var array 99 | */ 100 | public $sortable = [ 101 | 'order_column_name' => 'sort_order', 102 | ]; 103 | 104 | /** 105 | * The default rules that the model will validate against. 106 | * 107 | * @var array 108 | */ 109 | protected $rules = []; 110 | 111 | /** 112 | * Whether the model should throw a 113 | * ValidationException if it fails validation. 114 | * 115 | * @var bool 116 | */ 117 | protected $throwValidationExceptions = true; 118 | 119 | /** 120 | * Create a new Eloquent model instance. 121 | * 122 | * @param array $attributes 123 | */ 124 | public function __construct(array $attributes = []) 125 | { 126 | $this->setTable(config('rinvex.tags.tables.tags')); 127 | $this->mergeRules([ 128 | 'slug' => 'required|alpha_dash|max:150|unique:'.config('rinvex.tags.models.tag').',slug', 129 | 'name' => 'required|string|strip_tags|max:150', 130 | 'description' => 'nullable|string|max:32768', 131 | 'sort_order' => 'nullable|integer|max:100000', 132 | 'group' => 'nullable|string|strip_tags|max:150', 133 | ]); 134 | 135 | parent::__construct($attributes); 136 | } 137 | 138 | /** 139 | * Get all attached models of the given class to the tag. 140 | * 141 | * @param string $class 142 | * 143 | * @return \Illuminate\Database\Eloquent\Relations\MorphToMany 144 | */ 145 | public function entries(string $class): MorphToMany 146 | { 147 | return $this->morphedByMany($class, 'taggable', config('rinvex.tags.tables.taggables'), 'tag_id', 'taggable_id', 'id', 'id'); 148 | } 149 | 150 | /** 151 | * Get the options for generating the slug. 152 | * 153 | * @return \Spatie\Sluggable\SlugOptions 154 | */ 155 | public function getSlugOptions(): SlugOptions 156 | { 157 | return SlugOptions::create() 158 | ->doNotGenerateSlugsOnUpdate() 159 | ->generateSlugsFrom('name') 160 | ->saveSlugsTo('slug'); 161 | } 162 | 163 | /** 164 | * Get first tag(s) by name or create if not exists. 165 | * 166 | * @param mixed $tags 167 | * @param string|null $group 168 | * @param string|null $locale 169 | * 170 | * @return \Illuminate\Support\Collection 171 | */ 172 | public static function findByNameOrCreate($tags, string $group = null, string $locale = null): Collection 173 | { 174 | $locale = $locale ?? app()->getLocale(); 175 | 176 | return collect(Taggable::parseDelimitedTags($tags))->map(function (string $tag) use ($group, $locale) { 177 | return static::firstByName($tag, $group, $locale) ?: static::createByName($tag, $group, $locale); 178 | }); 179 | } 180 | 181 | /** 182 | * Find tag by name. 183 | * 184 | * @param mixed $tags 185 | * @param string|null $group 186 | * @param string|null $locale 187 | * 188 | * @return \Illuminate\Support\Collection 189 | */ 190 | public static function findByName($tags, string $group = null, string $locale = null): Collection 191 | { 192 | $locale = $locale ?? app()->getLocale(); 193 | 194 | return collect(Taggable::parseDelimitedTags($tags))->map(function (string $tag) use ($group, $locale) { 195 | return ($exists = static::firstByName($tag, $group, $locale)) ? $exists->getKey() : null; 196 | })->filter()->unique(); 197 | } 198 | 199 | /** 200 | * Get first tag by name. 201 | * 202 | * @param string $tag 203 | * @param string|null $group 204 | * @param string|null $locale 205 | * 206 | * @return static|null 207 | */ 208 | public static function firstByName(string $tag, string $group = null, string $locale = null) 209 | { 210 | $locale = $locale ?? app()->getLocale(); 211 | 212 | return static::query()->where("name->{$locale}", $tag)->when($group, function (Builder $builder) use ($group) { 213 | return $builder->where('group', $group); 214 | })->first(); 215 | } 216 | 217 | /** 218 | * Create tag by name. 219 | * 220 | * @param string $tag 221 | * @param string|null $locale 222 | * @param string|null $group 223 | * 224 | * @return static 225 | */ 226 | public static function createByName(string $tag, string $group = null, string $locale = null): self 227 | { 228 | $locale = $locale ?? app()->getLocale(); 229 | 230 | return static::create([ 231 | 'name' => [$locale => $tag], 232 | 'group' => $group, 233 | ]); 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /src/Providers/TagsServiceProvider.php: -------------------------------------------------------------------------------- 1 | mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'rinvex.tags'); 37 | 38 | // Bind eloquent models to IoC container 39 | $this->registerModels([ 40 | 'rinvex.tags.tag' => Tag::class, 41 | ]); 42 | 43 | // Register console commands 44 | $this->commands($this->commands); 45 | } 46 | 47 | /** 48 | * {@inheritdoc} 49 | */ 50 | public function boot() 51 | { 52 | // Register paths to be published by the publish command. 53 | $this->publishConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'rinvex/tags'); 54 | $this->publishMigrationsFrom(realpath(__DIR__.'/../../database/migrations'), 'rinvex/tags'); 55 | 56 | ! $this->app['config']['rinvex.tags.autoload_migrations'] || $this->loadMigrationsFrom(realpath(__DIR__.'/../../database/migrations')); 57 | 58 | // Map relations 59 | Relation::morphMap([ 60 | 'tag' => config('rinvex.tags.models.tag'), 61 | ]); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/Traits/Taggable.php: -------------------------------------------------------------------------------- 1 | morphToMany(config('rinvex.tags.models.tag'), 'taggable', config('rinvex.tags.tables.taggables'), 'taggable_id', 'tag_id') 73 | ->orderBy('sort_order') 74 | ->withTimestamps(); 75 | } 76 | 77 | /** 78 | * Get tags delimiter. 79 | * 80 | * @return string 81 | */ 82 | public static function getTagsDelimiter() 83 | { 84 | return static::$tagsDelimiter; 85 | } 86 | 87 | /** 88 | * Set tags delimiter. 89 | * 90 | * @param string $delimiter 91 | * 92 | * @return void 93 | */ 94 | public static function setTagsDelimiter(string $delimiter) 95 | { 96 | static::$tagsDelimiter = $delimiter; 97 | } 98 | 99 | /** 100 | * Boot the taggable trait for the model. 101 | * 102 | * @return void 103 | */ 104 | public static function bootTaggable() 105 | { 106 | static::deleted(function (self $model) { 107 | // Check if this is a soft delete or not by checking if `SoftDeletes::isForceDeleting` method exists 108 | (method_exists($model, 'isForceDeleting') && ! $model->isForceDeleting()) || $model->tags()->detach(); 109 | }); 110 | } 111 | 112 | /** 113 | * Attach the given tag(s) to the model. 114 | * 115 | * @param mixed $tags 116 | * 117 | * @return void 118 | */ 119 | public function setTagsAttribute($tags): void 120 | { 121 | static::saved(function (self $model) use ($tags) { 122 | $model->syncTags($tags); 123 | }); 124 | } 125 | 126 | /** 127 | * Scope query with all the given tags. 128 | * 129 | * @param \Illuminate\Database\Eloquent\Builder $builder 130 | * @param mixed $tags 131 | * @param string|null $group 132 | * @param string|null $locale 133 | * 134 | * @return \Illuminate\Database\Eloquent\Builder 135 | */ 136 | public function scopeWithAllTags(Builder $builder, $tags, string $group = null, string $locale = null): Builder 137 | { 138 | $tags = $this->parseTags($tags, $group, $locale); 139 | 140 | collect($tags)->each(function ($tag) use ($builder, $group) { 141 | $builder->whereHas('tags', function (Builder $builder) use ($tag, $group) { 142 | return $builder->where('id', $tag)->when($group, function (Builder $builder) use ($group) { 143 | return $builder->where('group', $group); 144 | }); 145 | }); 146 | }); 147 | 148 | return $builder; 149 | } 150 | 151 | /** 152 | * Scope query with any of the given tags. 153 | * 154 | * @param \Illuminate\Database\Eloquent\Builder $builder 155 | * @param mixed $tags 156 | * @param string|null $group 157 | * @param string|null $locale 158 | * 159 | * @return \Illuminate\Database\Eloquent\Builder 160 | */ 161 | public function scopeWithAnyTags(Builder $builder, $tags, string $group = null, string $locale = null): Builder 162 | { 163 | $tags = $this->parseTags($tags, $group, $locale); 164 | 165 | return $builder->whereHas('tags', function (Builder $builder) use ($tags, $group) { 166 | $builder->whereIn('id', $tags)->when($group, function (Builder $builder) use ($group) { 167 | return $builder->where('group', $group); 168 | }); 169 | }); 170 | } 171 | 172 | /** 173 | * Scope query without any of the given tags. 174 | * 175 | * @param \Illuminate\Database\Eloquent\Builder $builder 176 | * @param mixed $tags 177 | * @param string|null $group 178 | * @param string|null $locale 179 | * 180 | * @return \Illuminate\Database\Eloquent\Builder 181 | */ 182 | public function scopeWithoutTags(Builder $builder, $tags, string $group = null, string $locale = null): Builder 183 | { 184 | $tags = $this->parseTags($tags, $group, $locale); 185 | 186 | return $builder->whereDoesntHave('tags', function (Builder $builder) use ($tags, $group) { 187 | $builder->whereIn('id', $tags)->when($group, function (Builder $builder) use ($group) { 188 | return $builder->where('group', $group); 189 | }); 190 | }); 191 | } 192 | 193 | /** 194 | * Scope query without any tags. 195 | * 196 | * @param \Illuminate\Database\Eloquent\Builder $builder 197 | * 198 | * @return \Illuminate\Database\Eloquent\Builder 199 | */ 200 | public function scopeWithoutAnyTags(Builder $builder): Builder 201 | { 202 | return $builder->doesntHave('tags'); 203 | } 204 | 205 | /** 206 | * Determine if the model has any of the given tags. 207 | * 208 | * @param mixed $tags 209 | * @param string $group 210 | * @param string $locale 211 | * 212 | * @return bool 213 | */ 214 | public function hasAnyTags($tags, string $group = null, string $locale = null): bool 215 | { 216 | $tags = $this->parseTags($tags, $group, $locale); 217 | 218 | return ! $this->tags->pluck('id')->intersect($tags)->isEmpty(); 219 | } 220 | 221 | /** 222 | * Determine if the model has all of the given tags. 223 | * 224 | * @param mixed $tags 225 | * @param string $group 226 | * @param string $locale 227 | * 228 | * @return bool 229 | */ 230 | public function hasAllTags($tags, string $group = null, string $locale = null): bool 231 | { 232 | $tags = $this->parseTags($tags, $group, $locale); 233 | 234 | return collect($tags)->diff($this->tags->pluck('id'))->isEmpty(); 235 | } 236 | 237 | /** 238 | * Parse delimited tags. 239 | * 240 | * @param mixed $tags 241 | * 242 | * @return array 243 | */ 244 | public static function parseDelimitedTags($tags): array 245 | { 246 | if (is_string($tags) && mb_strpos($tags, static::$tagsDelimiter) !== false) { 247 | $delimiter = preg_quote(static::$tagsDelimiter, '#'); 248 | $tags = array_map('trim', preg_split("#[{$delimiter}]#", $tags, -1, PREG_SPLIT_NO_EMPTY)); 249 | } 250 | 251 | return array_unique(array_filter((array) $tags)); 252 | } 253 | 254 | /** 255 | * Attach model tags. 256 | * 257 | * @param mixed $tags 258 | * 259 | * @return $this 260 | */ 261 | public function attachTags($tags) 262 | { 263 | // Use 'sync' not 'attach' to avoid Integrity constraint violation 264 | $this->tags()->sync($this->parseTags($tags), false); 265 | 266 | return $this; 267 | } 268 | 269 | /** 270 | * Sync model tags. 271 | * 272 | * @param mixed $tags 273 | * @param bool $detaching 274 | * 275 | * @return $this 276 | */ 277 | public function syncTags($tags, bool $detaching = true) 278 | { 279 | $this->tags()->sync($this->parseTags($tags, null, null, true), $detaching); 280 | 281 | return $this; 282 | } 283 | 284 | /** 285 | * Detach model tags. 286 | * 287 | * @param mixed $tags 288 | * 289 | * @return $this 290 | */ 291 | public function detachTags($tags = null) 292 | { 293 | ! $tags || $tags = $this->parseTags($tags); 294 | 295 | $this->tags()->detach($tags); 296 | 297 | return $this; 298 | } 299 | 300 | /** 301 | * Parse tags. 302 | * 303 | * @param mixed $rawTags 304 | * @param string $group 305 | * @param string $locale 306 | * @param bool $create 307 | * 308 | * @return array 309 | */ 310 | protected function parseTags($rawTags, string $group = null, string $locale = null, $create = false): array 311 | { 312 | (is_iterable($rawTags) || is_null($rawTags)) || $rawTags = [$rawTags]; 313 | 314 | [$strings, $tags] = collect($rawTags)->map(function ($tag) { 315 | ! is_numeric($tag) || $tag = (int) $tag; 316 | 317 | ! $tag instanceof Model || $tag = [$tag->getKey()]; 318 | ! $tag instanceof Collection || $tag = $tag->modelKeys(); 319 | ! $tag instanceof BaseCollection || $tag = $tag->toArray(); 320 | 321 | return $tag; 322 | })->partition(function ($item) { 323 | return is_string($item); 324 | }); 325 | 326 | return $tags->merge(app('rinvex.tags.tag')->{$create ? 'findByNameOrCreate' : 'findByName'}($strings->toArray(), $group, $locale)->pluck('id'))->toArray(); 327 | } 328 | } 329 | --------------------------------------------------------------------------------