Enums are a powerful programming construct that let you define a set of named constants. In Laravel, using enums can make your code cleaner, more readable, and less error-prone.
In this tutorial, we will implement the Laravel ENUM package by Cerbero, which introduces an Artisan command to generate Enum classes effortlessly. We will create an Enum class for different image sizes commonly used on websites and later call this Enum in our controllers when resizing images.
Why Use Laravel ENUM Package?
The package provides a simple way to define Enum classes with constants that represent fixed values. This approach improves maintainability by centralizing your constants and providing useful utility methods.
You can explore more on the package on its GitHub repository.
Installation
Installing the package is straightforward via Composer:
composer require cerbero/laravel-enum
Once installed, you are ready to create your Enum classes using Artisan commands.
Creating an Enum for Image Sizes
We will define an Enum for various image sizes often used on the website. To generate the Enum class, run:
php artisan make:enum ImageSizes 'SIZE_150x150|SIZE_240x240|SIZE_300x188|SIZE_525x328|SIZE_580x363|SIZE_768x480|SIZE_1024x680|SIZE_1536x690'
This creates a class in app\Enums\ImageSizes.php that looks like this:
?php
namespace App\Enums;
class ImageSizes extends Enum
{
const SIZE_150x150 = 'size_150x150';
const SIZE_240x240 = 'size_240x240';
const SIZE_300x188 = 'size_300x188';
const SIZE_525x328 = 'size_525x328';
const SIZE_580x363 = 'size_580x363';
const SIZE_768x480 = 'size_768x480';
const SIZE_1024x680 = 'size_1024x680';
const SIZE_1536x690 = 'size_1536x690';
}
Adding a Map Function for Readable Values
To make these values easier to use within your controller, you can add a map function that returns user-friendly strings:
public static function map(): array
{
return [
static::SIZE_150x150 = '150x150',
static::SIZE_240x240 = '240x240',
static::SIZE_300x188 = '300x188',
static::SIZE_525x328 = '525x328',
static::SIZE_580x363 = '580x363',
static::SIZE_768x480 = '768x480',
static::SIZE_1024x680 = '1024x680',
static::SIZE_1536x690 = '1536x690',
];
}
Using the Enum in Your Controller
Now you can easily call the Enum values in your controller like this:
?php
$imagesSizes = ImageSizes::values(); dd($imagesSizes);
// This will output:
array:8 [
0 = "150x150"
1 = "240x240"
2 = "300x188"
3 = "525x328"
4 = "580x363"
5 = "768x480"
6 = "1024x680"
7 = "1536x690"
]
Conclusion
By implementing the Laravel ENUM package, you centralize and standardize fixed constants making your Laravel project more maintainable and easier to read. This is especially helpful when dealing with sets of predefined values, such as image sizes, roles, statuses, and more.
Explore the Laravel Enum Package GitHub repository for more features and advanced usage.
Feel free to reach out if you want a deeper dive or have questions on other Laravel packages!
Comments: