### Install CodeIgniter Tags via Composer Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/installation.md This command installs the CodeIgniter Tags library using Composer. Ensure Composer is installed and accessible in your project's root directory. ```console composer require michalsn/codeigniter-tags ``` -------------------------------- ### Install CodeIgniter Tags and Run Migrations Source: https://context7.com/michalsn/codeigniter-tags/llms.txt This snippet shows how to install the CodeIgniter Tags library using Composer and subsequently run the database migrations to create the necessary tables for tag storage. ```bash # Install via Composer composer require michalsn/codeigniter-tags # Run migrations to create tags and taggable tables php spark migrate --all ``` -------------------------------- ### Configure Autoloading for Manual Installation Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/installation.md This PHP code snippet demonstrates how to configure the CodeIgniter autoloader to include the CodeIgniter Tags library. It involves adding the library's namespace to the `$psr4` array and including the `Common.php` file in the `$files` array within `app/Config/Autoload.php`. ```php APPPATH, 'Config' => APPPATH . 'Config', 'Michalsn\CodeIgniterTags' => APPPATH . 'ThirdParty/tags/src', ]; // ... public $files = [ APPPATH . 'ThirdParty/tags/src/Common.php', ]; ``` -------------------------------- ### Migrate Database for CodeIgniter Tags Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/installation.md This command runs all pending database migrations, which is necessary to add the required tables for the CodeIgniter Tags library. This command should be executed from your project's root directory. ```console php spark migrate --all ``` -------------------------------- ### Searching Tags for Autocomplete in PHP Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/basic_usage.md Provides examples of using the `search` method in `TagModel` for autocomplete functionality. It shows how to search for tags based on a query string, optionally filtering by model type, and controlling the number of results and page. ```php model(TagModel::class)->search('po'); model(TagModel::class)->search('po', 'countries'); $perPage = 5; $page = 0; model(TagModel::class)->search('po', null, $perPage, $page); ``` -------------------------------- ### Publish Configuration File (Bash) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt To customize the tag cleanup behavior, you can publish the configuration file using the `tags:publish` Spark command. This will create the `app/Config/Tags.php` file, allowing you to modify settings like `cleanupUnusedTags`. ```bash # Publish config file to app/Config/Tags.php php spark tags:publish ``` -------------------------------- ### Retrieve Records with Tags using withTags() (PHP) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Demonstrates how to fetch records along with their associated tags using the `withTags()` query method. The tags are returned as a `Collection` object attached to the record's `tags` property. ```php withTags()->find(1); // Result: object with 'tags' property containing Collection // Get all records with tags $images = model(ImageModel::class)->withTags()->findAll(); // Iterate over tags (Collection requires items() method) foreach ($image->tags->items() as $tag) { echo "Name: {$tag->name}, Slug: {$tag->slug}\n"; } // Output: // Name: nature, Slug: nature // Name: sunset, Slug: sunset // Name: landscape, Slug: landscape ``` -------------------------------- ### Retrieving Model Results with All Specified Tags in PHP Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/basic_usage.md Demonstrates how to retrieve model records that possess all of the specified tags using the `withAllTags()` method. This method filters results to include only those matching every tag in the provided list. ```php model(ImageModel::class)->withAllTags(['tag1', 'tag2'])->findAll(); ``` -------------------------------- ### Retrieving Model Results with Any Specified Tags in PHP Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/basic_usage.md Shows how to fetch model records that have at least one of the specified tags using the `withAnyTags()` method. This method returns results matching any tag in the provided list. ```php model(ImageModel::class)->withAnyTags(['tag1', 'tag2'])->findAll(); ``` -------------------------------- ### Working with Tags on an Entity in PHP Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/basic_usage.md Demonstrates using the `TaggableEntity` trait to directly manipulate tags on an entity. This includes setting, adding, and removing tags, followed by saving the changes to the model. ```php $model = model(ImageModel::class); $image = $model->find(1); // set tags $image->tags = ['tag1', 'tag2']; // add a new tag $image->addTags(['tag3']); // remove tag $image->removeTags(['tag2']); // save changes with tags: tag1 and tag3 $model->save($image); ``` -------------------------------- ### Helper Function - convert_to_tags() Source: https://context7.com/michalsn/codeigniter-tags/llms.txt The `convert_to_tags()` helper function standardizes various tag input formats (string, array, Collection, Tag entity) into a Collection of Tag entities. ```APIDOC ## POST /api/tags/convert ### Description Converts various tag input formats into a standardized Collection of Tag entities. ### Method POST ### Endpoint `/api/tags/convert` ### Request Body - **input** (string|array|object) - Required - The tag input in string, array, or Tag entity format. ### Request Example ```json { "input": "nature,sunset,landscape" } ``` ### Response #### Success Response (200) - **tags** (array) - A Collection of Tag entities. #### Response Example ```json { "tags": [ {"id": null, "name": "nature", "slug": "nature"}, {"id": null, "name": "sunset", "slug": "sunset"}, {"id": null, "name": "landscape", "slug": "landscape"} ] } ``` ``` -------------------------------- ### Configuration Options Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Customize the tag cleanup behavior by publishing and modifying the configuration file (`app/Config/Tags.php`). The `cleanupUnusedTags` option controls whether unused tags are automatically deleted. ```APIDOC ## PUT /api/config/tags ### Description Updates the tag configuration settings. ### Method PUT ### Endpoint `/api/config/tags` ### Request Body - **cleanupUnusedTags** (boolean) - Optional - When true, tags not assigned to any record are automatically deleted during update operations. Defaults to true. ### Request Example ```json { "cleanupUnusedTags": false } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the configuration has been updated. #### Response Example ```json { "message": "Tag configuration updated successfully." } ``` ``` -------------------------------- ### Retrieving Tags by Model Type in PHP Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/basic_usage.md Illustrates how to fetch tags associated with specific models (tables) using the `findByTypes()` method in `TagModel`. This is useful for retrieving all tags used with a given set of models. ```php model(TagModel::class)->findByTypes(['images', 'news']); ``` -------------------------------- ### Retrieving Model Results with Tags in PHP Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/basic_usage.md Explains how to fetch model records that include their associated tags using the `withTags()` method. This method is compatible with other CodeIgniter Model query builders like `find()` and `findAll()`. ```php model(ImageModel::class)->withTags()->find(1); // or model(ImageModel::class)->withTags()->findAll(); ``` -------------------------------- ### Initialize Tags in CodeIgniter Model Source: https://github.com/michalsn/codeigniter-tags/blob/develop/README.md Demonstrates how to add the `HasTags` trait to a CodeIgniter model and initialize the tag functionality using the `initTags()` method within the model's `initialize()` method. This is a core step for enabling tag features on a model. ```php class ExampleModel extends BaseModel { use HasTags; // ... protected function initialize() { $this->initTags(); } // ... } ``` -------------------------------- ### Filter Records by All Specified Tags using withAllTags() (PHP) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Explains how to filter records to find those that possess ALL of the specified tags using the `withAllTags()` method. This is useful for precise querying where multiple tag conditions must be met simultaneously. ```php withAllTags(['nature', 'sunset']) ->findAll(); // Only returns images that have both tags assigned // Images with only 'nature' or only 'sunset' are NOT included // Can be combined with other query methods $images = model(ImageModel::class) ->withAllTags(['nature', 'landscape']) ->where('width >=', 1920) ->orderBy('created_at', 'DESC') ->findAll(10); ``` -------------------------------- ### Insert Records with Tags (PHP) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Illustrates how to insert new records into a model that has the `HasTags` trait enabled. Tags can be provided as a comma-separated string or an array, and non-existent tags will be automatically created. ```php insert([ 'name' => 'sunset.jpg', 'width' => 1920, 'height' => 1080, 'tags' => 'nature,sunset,landscape', ]); // Insert with tags as array model(ImageModel::class)->insert([ 'name' => 'portrait.jpg', 'width' => 800, 'height' => 1200, 'tags' => ['portrait', 'photography', 'studio'], ]); // Returns the insert ID (e.g., 1) ``` -------------------------------- ### Adding Tags to a Model in PHP Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/basic_usage.md Demonstrates how to add tags to a model record using the insert method. Tags can be provided as a comma-separated string or an array. Ensure tags are validated before saving. ```php model(ImageModel::class)->insert([ 'name' => 'sampleFile.jpeg', 'width' => 100, 'height' => 100, // this is our field with tags // we can also set it as an array: ['tag1', 'tag2', 'tag3'] 'tags' => 'tag1,tag2,tag3', ]); ``` -------------------------------- ### Helper Function - convert_to_tags() (PHP) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt The `convert_to_tags()` helper function standardizes various tag input formats (comma-separated strings, arrays, Collections, or single Tag entities) into a `Collection` of `Tag` entities. This simplifies tag handling, especially when manually adding tags to an entity's tag collection. ```php 'featured'])); // Practical use: manually add tags to existing set $model = model(ImageModel::class); $image = $model->withTags()->find(1); // Add a new tag to Collection $image->tags->push(convert_to_tags('new-tag')); // Note: Use entity methods (addTags) when TaggableEntity trait is available ``` -------------------------------- ### Filtering Records by Tags - withAnyTags() Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Use `withAnyTags()` to retrieve records that are associated with any of the specified tags. This is useful for finding items that match at least one tag in a given list. ```APIDOC ## GET /api/records ### Description Retrieves records that have any of the specified tags. ### Method GET ### Endpoint `/api/records` ### Query Parameters - **tags** (array) - Required - A list of tag names to filter by. ### Request Example ``` GET /api/records?tags[]=nature&tags[]=portrait&tags[]=studio ``` ### Response #### Success Response (200) - **records** (array) - A list of records matching any of the provided tags. #### Response Example ```json { "records": [ { "id": 1, "name": "Image 1", "tags": ["nature", "landscape"] }, { "id": 2, "name": "Image 2", "tags": ["portrait", "studio"] } ] } ``` ``` -------------------------------- ### Convert String to Tag Object in PHP Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/basic_usage.md This PHP snippet demonstrates how to use the convert_to_tags() function to simplify adding a new tag to an existing collection of tags associated with an image model. It contrasts the simplified approach with the more verbose method of manually creating a new Tag object. This function is particularly useful when entity classes are not in use or when direct manipulation of tags is needed before database persistence. ```php $model = model(ImageModel::class); $image = $model->withTags()->find(1); // instead of writing code like this: $image->tags->push(new Tag(['name' => 'second tag'])); // we can simplify it to this: $image->tags->push(convert_to_tags('second tag')); ``` -------------------------------- ### Iterating Through Tags in PHP Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/basic_usage.md Explains how to access and iterate through tags associated with a model record. Tags are returned as a Collection, allowing access to individual tag properties like 'name' and 'slug'. ```php $image = model(ImageModel::class)->withTags()->find(1); // tags are available as a Collection foreach ($image->tags->items() as $tag) { d($tag->name, $tag->slug); } ``` -------------------------------- ### TagModel - Search Tags for Autocomplete Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Use the `search()` method on `TagModel` to find tags, optionally filtering by model type. This is ideal for building tag autocomplete features. ```APIDOC ## GET /api/tags/search ### Description Searches for tags based on a prefix and optionally filters by model type. ### Method GET ### Endpoint `/api/tags/search` ### Query Parameters - **term** (string) - Required - The prefix to search for tags. - **type** (string) - Optional - The model type (table name) to filter tags by. - **perPage** (integer) - Optional - The number of results per page. - **page** (integer) - Optional - The page number for pagination. ### Request Example ``` GET /api/tags/search?term=po&type=images&perPage=10&page=0 ``` ### Response #### Success Response (200) - **tags** (array) - A list of tag objects matching the search criteria. #### Response Example ```json { "tags": [ {"id": 1, "name": "Potato", "slug": "potato"}, {"id": 2, "name": "Portugal", "slug": "portugal"} ] } ``` ``` -------------------------------- ### Configuration Options - cleanupUnusedTags (PHP) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt The `app/Config/Tags.php` file allows you to configure tag cleanup behavior. Setting `$cleanupUnusedTags` to `true` (the default) automatically deletes tags not assigned to any record during update operations. Setting it to `false` preserves orphaned tags, which can be useful for autocomplete suggestions. ```php withAnyTags(['nature', 'portrait', 'studio']) ->findAll(); // Returns images that have at least one of the specified tags // Combine with pagination $images = model(ImageModel::class) ->withAnyTags(['featured', 'popular', 'trending']) ->paginate(20); ``` -------------------------------- ### Entity Tag Manipulation Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Manipulate tags directly on entity instances using `setTags()`, `addTags()`, and `removeTags()` before saving. These methods allow for setting, adding, and removing tags from an entity. ```APIDOC ## PUT /api/entities/{id} ### Description Updates tags for a specific entity. ### Method PUT ### Endpoint `/api/entities/{id}` ### Path Parameters - **id** (integer) - Required - The ID of the entity to update. ### Request Body - **set_tags** (array) - Optional - An array of tags to set, replacing all existing tags. - **add_tags** (array) - Optional - An array of tags to add to the existing set. - **remove_tags** (array) - Optional - An array of tags to remove from the existing set. ### Request Example ```json { "set_tags": ["photography", "portrait"], "add_tags": ["studio", "professional"], "remove_tags": ["portrait"] } ``` ### Response #### Success Response (200) - **entity** (object) - The updated entity with its new tag set. #### Response Example ```json { "entity": { "id": 1, "name": "Updated Image", "tags": ["photography", "studio", "professional"] } } ``` ``` -------------------------------- ### TagModel - Search Tags for Autocomplete (PHP) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt The `TagModel::search()` method is designed for building autocomplete functionalities. It allows searching tags by a prefix, optionally filtering by model type (table name), and controlling pagination. The results can be easily formatted for AJAX responses. ```php search('po'); // Returns: Potato, Portugal, Poster, etc. // Search tags only used in 'images' table $tags = model(TagModel::class)->search('nat', 'images'); // Returns only tags starting with 'nat' that are assigned to images // Control pagination: 10 results per page, page 0 (first page) $perPage = 10; $page = 0; $tags = model(TagModel::class)->search('ph', null, $perPage, $page); // For AJAX autocomplete endpoint $term = $request->getGet('term'); $type = $request->getGet('type'); // optional $tags = model(TagModel::class)->search($term, $type, 5, 0); return $this->response->setJSON( array_map(fn($tag) => ['id' => $tag->id, 'name' => $tag->name], $tags) ); ``` -------------------------------- ### TagModel - Find Tags by Names Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Look up specific tags by their exact names using `findByNames()`. This method returns a list of tag entities that match the provided names. ```APIDOC ## GET /api/tags/names ### Description Retrieves tags based on their exact names. ### Method GET ### Endpoint `/api/tags/names` ### Query Parameters - **names** (array) - Required - An array of tag names to search for. ### Request Example ``` GET /api/tags/names?names[]=nature&names[]=portrait&names[]=landscape ``` ### Response #### Success Response (200) - **tags** (array) - A list of tag objects matching the provided names. #### Response Example ```json { "tags": [ {"id": 1, "name": "nature", "slug": "nature"}, {"id": 2, "name": "portrait", "slug": "portrait"}, {"id": 3, "name": "landscape", "slug": "landscape"} ] } ``` ``` -------------------------------- ### TagModel - Find Tags by Types (Tables) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Retrieve all tags associated with specific model types (tables) using `findByTypes()`. This is useful for displaying tag clouds or lists for particular sections of your application. ```APIDOC ## GET /api/tags/types ### Description Retrieves tags based on the model types (tables) they are associated with. ### Method GET ### Endpoint `/api/tags/types` ### Query Parameters - **types** (array) - Required - An array of model type names (table names) to filter tags by. ### Request Example ``` GET /api/tags/types?types[]=images&types[]=articles ``` ### Response #### Success Response (200) - **tags** (array) - A list of tag objects associated with the specified types. #### Response Example ```json { "tags": [ {"id": 1, "name": "nature", "slug": "nature"}, {"id": 2, "name": "photography", "slug": "photography"}, {"id": 3, "name": "technology", "slug": "technology"} ] } ``` ``` -------------------------------- ### Update Tags on Existing Records (PHP) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Shows how to update the tags associated with an existing record using the `save()` method. This operation replaces all current tags with the new set provided. Empty strings or arrays will remove all tags. ```php save([ 'id' => 1, 'tags' => 'nature,mountains,hiking', ]); // Update tags using array format model(ImageModel::class)->save([ 'id' => 1, 'tags' => ['nature', 'mountains', 'hiking'], ]); // Remove all tags from a record model(ImageModel::class)->save([ 'id' => 1, 'tags' => '', // or empty array [] ]); ``` -------------------------------- ### Configure Entity with TaggableEntity Trait Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Shows how to add the `TaggableEntity` trait to a CodeIgniter 4 entity. This trait provides direct methods for managing tags on an entity instance, such as `addTags()`, `removeTags()`, and `setTags()`. ```php initTags(); } } ``` -------------------------------- ### TagModel - Find Tags by Names (PHP) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt The `TagModel::findByNames()` method allows you to look up specific tags by their exact names. It returns an array of Tag entities for all matching names, which can then be used to display tag details or link to related content. ```php findByNames(['nature', 'portrait', 'landscape']); // Returns array of Tag entities for matching names foreach ($tags as $tag) { echo "ID: {$tag->id}, Name: {$tag->name}, Slug: {$tag->slug}\n"; } ``` -------------------------------- ### Modifying Tags in a Model in PHP Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/basic_usage.md Shows how to modify existing tags for a model record using the save method. Tags can be updated by providing a new comma-separated string or an array. Backend validation is crucial. ```php model(ImageModel::class)->save([ 'id' => 1, // this is our field with tags // we can also set it as an array: ['tag1', 'tag2'] 'tags' => 'tag1,tag2', ]); ``` -------------------------------- ### Removing Tags from a Model in PHP Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/basic_usage.md Illustrates how to remove all tags from a model record by setting the 'tags' field to an empty string or an empty array using the save method. Backend validation is essential. ```php model(ImageModel::class)->save([ 'id' => 1, // this is our field with tags // we can also set it as an array: [] 'tags' => '', ]); ``` -------------------------------- ### Database Schema for CodeIgniter Tags Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Defines the SQL schema for the 'tags' and 'taggable' tables used by the CodeIgniter Tags library. The 'tags' table stores unique tag information, while the 'taggable' table handles polymorphic relationships between tags and other entities. ```sql -- tags table: stores unique tag entries CREATE TABLE tags ( id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(32) NOT NULL, -- Display name (max 32 chars) slug VARCHAR(32) NOT NULL UNIQUE, -- URL-safe slug created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL ); -- taggable table: polymorphic pivot table CREATE TABLE taggable ( tag_id INT(11) UNSIGNED, taggable_id INT(11) UNSIGNED, -- ID of tagged record taggable_type VARCHAR(32) NOT NULL, -- Table name (e.g., 'images') UNIQUE KEY (tag_id, taggable_id, taggable_type) ); ``` -------------------------------- ### Entity Tag Manipulation - setTags(), addTags(), removeTags() (PHP) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt When using the `TaggableEntity` trait, you can directly manipulate tags on entity instances before saving them to the database. This allows for setting, adding, and removing tags efficiently, including chaining operations. ```php find(1); // Set tags (replaces all existing tags) $image->setTags(['photography', 'portrait']); // Add tags to existing set $image->addTags(['studio', 'professional']); // Now has: photography, portrait, studio, professional // Remove specific tags $image->removeTags(['portrait']); // Now has: photography, studio, professional // Chain operations $image->setTags(['base']) ->addTags(['extra1', 'extra2']) ->removeTags(['extra1']); // Now has: base, extra2 // Save changes to database $model->save($image); ``` -------------------------------- ### TagModel - Find Tags by Types (Tables) (PHP) Source: https://context7.com/michalsn/codeigniter-tags/llms.txt Use the `TagModel::findByTypes()` method to retrieve all tags associated with specific model types (table names). This is particularly useful for displaying tag clouds or lists of tags relevant to particular sections of your application. ```php findByTypes(['images', 'articles']); // Get tags used only in images $imageTags = model(TagModel::class)->findByTypes(['images']); // Useful for displaying tag clouds per section foreach ($tags as $tag) { echo "{$tag->name}"; } ``` -------------------------------- ### Add TaggableEntity Trait to CodeIgniter Entity Source: https://github.com/michalsn/codeigniter-tags/blob/develop/README.md Shows how to incorporate the `TaggableEntity` trait into a CodeIgniter Entity class. This is necessary when using Entity classes to ensure they can interact with the tag system provided by the library. ```php class Example extends Entity { use TaggableEntity; // ... } ``` -------------------------------- ### Integrate HasTags Trait into CodeIgniter Model Source: https://github.com/michalsn/codeigniter-tags/blob/develop/docs/configuration.md Add the `HasTags` trait to your CodeIgniter model and call `initTags()` in the `initialize()` method. This allows your model to manage tags without altering the database schema or `$allowedFields`. ```php initTags(); } // ... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.