DEV Community

Cover image for Our way: Enums
Robson Tenório
Robson Tenório

Posted on • Edited on

Our way: Enums

👉 Go to Summary

There is no wrong or right way, there is our way.

-- Someone

.
.
.

Why not Enums?

Don't get me wrong: Enums are useful, but it is pretty "hardcoded".

We can do it better!

Better approach: use Models

Consider this migrations.

Schema::create('status', function (Blueprint $table) {
   $table->id();
   $table->string('name');
   $table->string('description');
   $table->string('color');
}

Schema::create('orders', function (Blueprint $table) {
   $table->id();
   $table->foreignId('status_id')->constrained();
   $table->decimal('amount');
}

Enter fullscreen mode Exit fullscreen mode

Consider this Models.

class Status extends Model 
{
   public const PENDING = 1;
   public const APPROVED = 2;
   public const DONE = 3;
}

class Order extends Model 
{
   public function status() 
   {
      return $this->belongsTo(Status::class);
   }
}
Enter fullscreen mode Exit fullscreen mode

It is done!

$orders = Order::with('status')->get();
Enter fullscreen mode Exit fullscreen mode
@foreach($orders as $order)

   <div>
       Order: {{ $order->id }} , {{ $order->amount }} 

       <!-- No needed `IF` to define a color ou print a human name -->
       <span class="{{ $order->status->color }}">
           {{ $order->status->name }}
       </span>

       <div class="text-sm">
           {{ $order->status->description }}
       </div>
   </div>

@endforeach

Enter fullscreen mode Exit fullscreen mode

Benefits

Making status as a Model:

  • Dynamic config.
  • No extra helpers or IFs to show status details.
  • It is easy to query.

Top comments (0)