### Install Laravel Magic Enums Source: https://github.com/synergitech/laravel-magic-enums/blob/main/README.md Installs the package using Composer for the PHP backend and npm for the frontend. These commands are essential for setting up the package in your project. ```sh composer require synergitech/laravel-magic-enums npm install --save laravel-magic-enums ``` -------------------------------- ### Define PHP Enum with Magic Enum Traits Source: https://github.com/synergitech/laravel-magic-enums/blob/main/README.md Defines a PHP enum that implements the MagicEnum interface and uses the HasMagic trait. This setup is required for the enum to be exportable to the frontend. ```php value => 'red', ]; } ``` -------------------------------- ### Configure Vite Plugin for Magic Enums Source: https://github.com/synergitech/laravel-magic-enums/blob/main/README.md Configures the Vite build tool to automatically regenerate enum exports when PHP enums change. This includes options for input, output, and formatting. ```js import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import vue from '@vitejs/plugin-vue'; import { laravelMagicEnums } from "laravel-magic-enums/vite"; export default defineConfig({ plugins: [ laravel({ ... }), vue({ ... }), laravelMagicEnums({ input: 'app/Enums', output: 'resources/js/my-enums', format: true, }), ], ... ``` -------------------------------- ### Generated Frontend Enum Output with Advanced Features Source: https://github.com/synergitech/laravel-magic-enums/blob/main/README.md Shows the resulting JavaScript object structure for a PHP enum that uses `AppendConstToMagic` and `AppendValueToMagic` attributes, illustrating how enums and their custom mappings are represented in the frontend. ```js TestingEnum: { First: { "name": "First", "value": "first", "colour": "red" }, Second: { "name": "Second", "value": "second", "colour": null }, Third: { "name": "Third", "value": "third", "colour": null } }, TestingEnumJustOne: { First: { "name": "First", "value": "first", "colour": "red" } } ``` -------------------------------- ### Generate JavaScript Enums with Artisan Command Source: https://context7.com/synergitech/laravel-magic-enums/llms.txt The `laravel-magic-enums:generate` Artisan command scans PHP enums and creates a JavaScript module. It supports custom input and output paths, and can optionally format the output using Prettier. ```bash php artisan laravel-magic-enums:generate # Custom input directory php artisan laravel-magic-enums:generate --input=app/Domain/Enums # Custom output directory php artisan laravel-magic-enums:generate --output=resources/js/enums # Format output with Prettier php artisan laravel-magic-enums:generate --format # Custom Prettier command php artisan laravel-magic-enums:generate --format --prettier="npx prettier" # Combined options php artisan laravel-magic-enums:generate \ --input=app/Enums \ --output=resources/js/magic-enums \ --format ``` -------------------------------- ### Extend PHP Enum Functionality with HasMagic Trait and Attributes Source: https://context7.com/synergitech/laravel-magic-enums/llms.txt Demonstrates how the HasMagic trait and attributes like `AppendConstToMagic` and `AppendValueToMagic` enhance PHP enums. These allow for the creation of sub-enums and the appending of additional properties (like 'color') to enum cases during serialization. The `getConsts()` method can retrieve attribute-decorated constants. ```php value => 'green', self::Medium->value => 'yellow', self::High->value => 'orange', self::Critical->value => 'red', ]; } // toMagicArray() output includes color property: // [ // 'Low' => ['name' => 'Low', 'value' => 'low', 'color' => 'green'], // 'Medium' => ['name' => 'Medium', 'value' => 'medium', 'color' => 'yellow'], // 'High' => ['name' => 'High', 'value' => 'high', 'color' => 'orange'], // 'Critical' => ['name' => 'Critical', 'value' => 'critical', 'color' => 'red'], // ] // getConsts() returns attribute-decorated constants $subEnums = Priority::getConsts(); // Returns: ['URGENT'] ``` -------------------------------- ### Update Frontend Enum Import (JavaScript) Source: https://github.com/synergitech/laravel-magic-enums/blob/main/UPGRADING.md This snippet shows the change in how enums are imported in the frontend JavaScript code when upgrading from laravel-magic-enums v2 to v3. The import path and the destructuring assignment are modified. ```javascript // Before: import { useEnums } from 'laravel-magic-enums'; const { YourEnum } = useEnums(); // After: import { enums } from 'resources/js/magic-enums'; const { YourEnum } = enums; ``` -------------------------------- ### Implement CustomMagic Trait in a Laravel Enum Source: https://context7.com/synergitech/laravel-magic-enums/llms.txt This PHP code demonstrates how to use the 'CustomMagic' trait within a Laravel enum ('DocumentType'). It implements the abstract methods required by 'CustomMagic' to provide specific labels, descriptions, and sort orders for each enum case, ensuring these are included in the generated magic array. ```php // Usage in enum: namespace App\Enums; use SynergiTech\MagicEnums\Interfaces\MagicEnum; use App\Traits\CustomMagic; enum DocumentType: string implements MagicEnum { use CustomMagic; case Invoice = 'invoice'; case Contract = 'contract'; case Report = 'report'; private static function getLabel(self $case): string { return match($case) { self::Invoice => 'Invoice Document', self::Contract => 'Legal Contract', self::Report => 'Business Report', }; } private static function getDescription(self $case): string { return match($case) { self::Invoice => 'Financial billing document', self::Contract => 'Legally binding agreement', self::Report => 'Analytics and insights', }; } private static function getSortOrder(self $case): int { return match($case) { self::Invoice => 1, self::Contract => 2, self::Report => 3, }; } } ``` -------------------------------- ### Using Generated JavaScript Magic Enums Source: https://context7.com/synergitech/laravel-magic-enums/llms.txt The generated JavaScript module exports an `enums` object containing all Magic Enums, wrapped in a Proxy for flexible access and frozen for immutability. This allows for easy consumption in frontend frameworks. ```javascript // Import the generated enums (default path: resources/js/magic-enums/index.js) import { enums } from 'resources/js/magic-enums/index.js'; // Destructure specific enums const { PaymentStatus, UserRole, UserRoleStaff } = enums; // Access enum cases console.log(PaymentStatus.Completed); // { name: 'Completed', value: 'completed', icon: 'check-circle', badge_class: 'badge-success' } // Access enum value console.log(PaymentStatus.Completed.value); // 'completed' // Access appended properties console.log(PaymentStatus.Failed.icon); // 'x-circle' // Check if case exists (returns false for non-existent cases) console.log(PaymentStatus.NonExistent); // false // Use in Vue/React components function StatusBadge({ status }) { const statusEnum = PaymentStatus[status]; if (!statusEnum) return null; return ( {statusEnum.name} ); } // Iterate over enum cases Object.values(UserRole).forEach(role => { console.log(`${role.name}: ${role.value}`); }); // Use sub-enums for filtered selections const staffOptions = Object.values(UserRoleStaff).map(role => ({ label: role.name, value: role.value })); ``` -------------------------------- ### Extend HasMagic Trait for Custom Enum Serialization Source: https://context7.com/synergitech/laravel-magic-enums/llms.txt This PHP code defines a custom trait 'CustomMagic' that extends the 'HasMagic' trait from the laravel-magic-enums package. It overrides the 'toMagicArray' method to include additional custom properties like 'label', 'description', and 'sortOrder' for each enum case. ```php > */ public static function toMagicArray(?array $only = null): array { $info = self::parentToMagicArray($only); foreach (self::cases() as $case) { if ($only && !in_array($case, $only)) { continue; } // Add custom properties to each case $info[$case->name] = $info[$case->name] + [ 'label' => self::getLabel($case), 'description' => self::getDescription($case), 'sortOrder' => self::getSortOrder($case), ]; } return $info; } abstract private static function getLabel(self $case): string; abstract private static function getDescription(self $case): string; abstract private static function getSortOrder(self $case): int; } ``` -------------------------------- ### AppendValueToMagic Attribute for PHP Enums Source: https://context7.com/synergitech/laravel-magic-enums/llms.txt The AppendValueToMagic attribute allows mapping additional properties to enum cases. It requires an associative array where keys are enum values and values are the data to append. Cases not present in the mapping will default to null. ```php value => 'clock', self::Processing->value => 'spinner', self::Completed->value => 'check-circle', self::Failed->value => 'x-circle', self::Refunded->value => 'arrow-left', ]; #[AppendValueToMagic] public const BADGE_CLASS = [ self::Pending->value => 'badge-warning', self::Processing->value => 'badge-info', self::Completed->value => 'badge-success', self::Failed->value => 'badge-danger', self::Refunded->value => 'badge-secondary', ]; } // Generated JavaScript enum case example: // PaymentStatus.Completed = { // name: 'Completed', // value: 'completed', // icon: 'check-circle', // badge_class: 'badge-success' // } ``` -------------------------------- ### Define Sub-Enums using AppendConstToMagic Attribute Source: https://context7.com/synergitech/laravel-magic-enums/llms.txt Illustrates the use of the `AppendConstToMagic` attribute to define sub-enums within a main enum. Constants marked with this attribute must be arrays of enum cases. The package will generate separate JavaScript enums for each of these sub-enums, containing only the specified cases. ```php ['name' => 'Pending', 'value' => 'pending'], // 'Active' => ['name' => 'Active', 'value' => 'active'], // 'Completed' => ['name' => 'Completed', 'value' => 'completed'], // ] // Filter to specific cases $filtered = Status::toMagicArray(only: [Status::Pending, Status::Active]); // Returns only Pending and Active cases ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.