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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay