Laravel Optimization: The Power of Numeric Enums for Faster Queries

March 1, 2025

 

Enums were introduced in PHP 8.1.

 

 

Many developers store enum values as strings.

 

Because of the readability.

 

But the INT ones are better with speed

 


Why Use Numeric Values in Enums?

 

  • Faster database queries  
    numbers are compared much quicker than strings.

 

  • Smaller storage size
    TINYINT (1 byte) is more efficient than VARCHAR.

 


How to Store Enums Correctly in Laravel?

 

  • Use Backed Enums with Numeric Values:

 

enum QueueStatus: int  
{  
    case PENDING = 1;  
    case IN_PROGRESS = 2;  
    case FINALIZING = 3;  
    case VALIDATING = 4;  
    case SENT = 5;  
    case DOWNLOADED = 6;  
    case COMPLETED = 7;  
    case FULLY_COMPLETED = 8;  

    public function getSlug(): string  
    {  
        return strtolower(str_replace('_', '-', $this->name));  
    }  
}

 

  • Define columns with unsignedTinyInteger()

 

$table->unsignedTinyInteger('status')->default(QueueStatus::PENDING->value);

 

  • Type cast the model's columns

 

class QueueItem extends Model  
{  
    protected $casts = [  
        'status' => QueueStatus::class,  
    ];  
}

 


How Much Faster is TINYINT Compared to VARCHAR?

 

  • Indexed number queries are 2-5x faster than string queries

     

  • For tables with over 1 million rows, performance can be up to 5x better.

     

  • Smaller index sizes lead to faster database operations.