👉 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');
}
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);
}
}
It is done!
$orders = Order::with('status')->get();
@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
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)