PHP code example of masum / laravel-tagging

1. Go to this page and download the library: Download masum/laravel-tagging library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

masum / laravel-tagging example snippets


use Masum\Tagging\Traits\Tagable;

class Equipment extends Model
{
    use Tagable;

    // Required: Define display name for the model
    const TAGABLE = 'Equipment::Generic';

    protected $fillable = ['name', 'description'];
}

use Masum\Tagging\Models\TagConfig;

TagConfig::create([
    'model' => \App\Models\Equipment::class,  // Full namespace auto_generate' => true,
]);

$equipment = Equipment::create(['name' => 'Cisco Router']);

echo $equipment->tag;  // Output: EQ-001

$router2 = Equipment::create(['name' => 'TP-Link Switch']);
echo $router2->tag;    // Output: EQ-002

use Masum\Tagging\Models\TagConfig;

TagConfig::create([
    'model' => \App\Models\Equipment::class,  // Full namespace ding_length' => 3,
    'description' => 'Equipment tags'
]);

use App\Models\Equipment;

$eq1 = Equipment::create(['name' => 'Cisco Router']);
echo $eq1->tag;  // EQ-001

$eq2 = Equipment::create(['name' => 'TP-Link Switch']);
echo $eq2->tag;  // EQ-002

$eq3 = Equipment::create(['name' => 'Dell Server']);
echo $eq3->tag;  // EQ-003

use Masum\Tagging\Models\Tag;

// Get all tags
Tag::all();

// Count tags
Tag::count();  // 3

// View tag details
$tag = Tag::first();
echo "Tag: {$tag->value}\n";
echo "Type: {$tag->taggable_type}\n";
echo "ID: {$tag->taggable_id}\n";

// Find equipment by tag
$equipment = Equipment::byTag('EQ-001')->first();
echo $equipment->name;  // Cisco Router

// Search with pattern
Equipment::byTag('EQ-00%')->get();  // Returns all matching equipment

// Load all equipment with tags (prevents N+1 queries)
$allEquipment = Equipment::with('tag')->get();

foreach ($allEquipment as $eq) {
    echo "{$eq->name} -> {$eq->tag}\n";
}

// Output:
// Cisco Router -> EQ-001
// TP-Link Switch -> EQ-002
// Dell Server -> EQ-003

// When you delete equipment, tags are automatically deleted
$eq = Equipment::find(1);
$tagValue = $eq->tag;
$eq->delete();

// Verify tag was deleted
Tag::where('value', $tagValue)->first();  // null

use App\Models\Equipment;
use Masum\Tagging\Models\Tag;
use Masum\Tagging\Models\TagConfig;

echo "=== Laravel Tagging Quick Test ===\n\n";

// Create config if not exists
if (!TagConfig::where('model', \App\Models\Equipment::class)->exists()) {
    TagConfig::create([
        'model' => \App\Models\Equipment::class,
        'prefix' => 'EQ',
        'separator' => '-',
        'number_format' => 'sequential',
        'auto_generate' => true,
    ]);
    echo "✓ Config created\n";
}

// Create test equipment
$eq = Equipment::create(['name' => 'Test Item ' . time()]);
echo "✓ Equipment created: ID {$eq->id}\n";

// Check tag
if ($eq->tag) {
    echo "✓ Tag generated: {$eq->tag}\n";
} else {
    echo "✗ Tag NOT generated!\n";
}

// Verify in database
$tag = Tag::where('taggable_type', \App\Models\Equipment::class)
    ->where('taggable_id', $eq->id)
    ->first();

if ($tag) {
    echo "✓ Tag in database: {$tag->value}\n";
} else {
    echo "✗ Tag NOT in database!\n";
}

// Test search
$found = Equipment::byTag($eq->tag)->first();
if ($found && $found->id === $eq->id) {
    echo "✓ Tag search working\n";
} else {
    echo "✗ Tag search failed\n";
}

echo "\n=== All Tests Passed! ===\n";

EQ-001, EQ-002, EQ-003, ...

EQ-1698765432, EQ-1698765499, ...

SW-001-5, SW-002-5, SW-001-7
// Format: {PREFIX}-{NUMBER}-{BRANCH_ID}

// In your code
$tag = Tag::find(1);
$barcode = $tag->generateBarcodeSVG();  // SVG format
$png = $tag->generateBarcodePNG();      // PNG format
$base64 = $tag->getBarcodeBase64();     // Base64 data URL

use Masum\Tagging\Events\{TagCreated, TagUpdated, TagDeleted, TagGenerationFailed};

// Send webhook when tag is created
Event::listen(TagCreated::class, function ($event) {
    Http::post('https://api.example.com/webhooks/tag-created', [
        'tag' => $event->tag->value,
        'model' => get_class($event->taggable),
    ]);
});

// Log tag updates to audit trail
Event::listen(TagUpdated::class, function ($event) {
    AuditLog::create([
        'action' => 'tag_updated',
        'old_value' => $event->oldValue,
        'new_value' => $event->tag->value,
    ]);
});

// Alert on generation failures
Event::listen(TagGenerationFailed::class, function ($event) {
    Mail::to('[email protected]')->send(new TagFailedAlert($event));
});

return [
    // Database table names
    'tables' => [
        'tags' => 'tags',
        'tag_configs' => 'tag_configs',
    ],

    // Table prefix
    'table_prefix' => env('TAGGING_TABLE_PREFIX', 'tagging_'),

    // Fallback prefix when no config exists
    'fallback_prefix' => env('TAGGING_FALLBACK_PREFIX', 'TAG'),

    // Default values
    'defaults' => [
        'separator' => '-',
        'number_format' => 'sequential',
        'auto_generate' => true,
    ],

    // Caching configuration
    'cache' => [
        'enabled' => env('TAGGING_CACHE_ENABLED', true),
        'ttl' => env('TAGGING_CACHE_TTL', 3600),
        'driver' => env('TAGGING_CACHE_DRIVER', null),
    ],

    // Performance settings
    'performance' => [
        'max_retries' => env('TAGGING_MAX_RETRIES', 3),
        'lock_timeout' => env('TAGGING_LOCK_TIMEOUT', 10),
        'debug_n_plus_one' => env('TAGGING_DEBUG_N_PLUS_ONE', true),
    ],

    // API Routes
    'routes' => [
        'enabled' => env('TAGGING_ROUTES_ENABLED', true),
        'prefix' => 'api/tag-configs',
        'middleware' => ['api'],  // Add 'auth:sanctum' for authentication
    ],
];

$equipment = Equipment::find(1);

// Get tag value
echo $equipment->tag;  // EQ-001

// Get tag model
$tagModel = $equipment->tag();

// Get tag configuration
$config = $equipment->tag_config;

// Ensure tag exists (generate if missing)
$equipment->ensureTag();

// Generate next tag without saving
$nextTag = $equipment->generateNextTag();

// Set custom tag
$equipment->tag = 'CUSTOM-001';

// Remove tag
$equipment->tag = null;

use Masum\Tagging\Models\Tag;

// Find model by tag value
$tag = Tag::where('value', 'EQ-001')->first();
$equipment = $tag->taggable;

// Get all tags for a model type
$equipmentTags = Tag::where('taggable_type', \App\Models\Equipment::class)->get();

class Brand extends Model
{
    use Tagable;

    const TAGABLE = 'Brand';
    const TAG_LABEL = 'Brand: {name}';  // Variable interpolation

    protected $fillable = ['name'];
}

use Masum\Tagging\Exceptions\{TagGenerationException, DuplicateTagException};

try {
    $equipment = Equipment::create(['name' => 'Router']);
} catch (TagGenerationException $e) {
    Log::error('Tag generation failed', ['error' => $e->getMessage()]);
    // Assign manual tag or handle error
} catch (DuplicateTagException $e) {
    // Handle duplicate tag scenario
}

class Equipment extends Model
{
    use Tagable;

    protected function generateSequentialTag(TagConfig $tagConfig): string
    {
        // Custom logic here
        return parent::generateSequentialTag($tagConfig);
    }
}

// ❌ Bad - Creates N+1 queries
$equipment = Equipment::all();
foreach ($equipment as $item) {
    echo $item->tag;  // Separate query each time!
}

// ✅ Good - Single query for all tags
$equipment = Equipment::with('tag')->get();
foreach ($equipment as $item) {
    echo $item->tag;  // Uses loaded relationship
}

// First call: queries database
$config = TagConfig::forModel(\App\Models\Equipment::class);

// Subsequent calls: uses cache (1 hour default)
$config = TagConfig::forModel(\App\Models\Equipment::class);

// Atomic counter increment with SELECT FOR UPDATE
// Retries up to 3 times with exponential backoff
// Falls back to timestamp-based tags if all retries fail

// 1. Always validate inputs
$validated = $request->validate([
    'name' => 'dleware
'routes' => [
    'middleware' => ['api', 'auth:sanctum'],
],

// 3. Set APP_DEBUG=false in production
APP_DEBUG=false

// 4. Implement rate limiting
Route::middleware(['throttle:60,1'])->group(function () {
    // Tag routes
});

use Masum\Tagging\Traits\Tagable;

class Equipment extends Model
{
    use Tagable;  // ✅ Trait must be present

    const TAGABLE = 'Equipment::Generic';  // ✅ Required constant
}

TagConfig::create([
    'model' => Equipment::class,  // Missing namespace!
]);

TagConfig::create([
    'model' => \App\Models\Equipment::class,  // Full namespace hes
]);

$config = \Masum\Tagging\Models\TagConfig::where('model', \App\Models\Equipment::class)->first();

if (!$config) {
    echo "No configuration found!";
}

\Masum\Tagging\Models\TagConfig::create([
    'model' => \App\Models\Equipment::class,  // Must match exactly!
    'prefix' => 'EQ',
    'separator' => '-',
    'number_format' => 'sequential',
]);

// Find duplicates
$duplicates = \Masum\Tagging\Models\Tag::select('taggable_type', 'taggable_id')
    ->groupBy('taggable_type', 'taggable_id')
    ->havingRaw('COUNT(*) > 1')
    ->get();

// Delete duplicates (keeping the first)
foreach ($duplicates as $dup) {
    \Masum\Tagging\Models\Tag::where('taggable_type', $dup->taggable_type)
        ->where('taggable_id', $dup->taggable_id)
        ->orderBy('id')
        ->skip(1)
        ->delete();
}

$config = \Masum\Tagging\Models\TagConfig::where('model', \App\Models\Equipment::class)->first();
$config->update(['current_number' => 0]);  // Start from 1

// ❌ Bad
$equipment = Equipment::all();

// ✅ Good
$equipment = Equipment::with('tag')->get();
bash
php artisan vendor:publish --tag=tagging-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=tagging-config
bash
php artisan tinker
bash
php artisan vendor:publish --tag=tagging-config
bash
php artisan vendor:publish --tag=tagging-migrations
php artisan migrate