Skip to main content

Static String Letters to PHP Enum

Premium
4 min read

The next thing I suggest fixing is hard-coded letters as Order statuses.

I found these 'P', 'F', and 'C' in the Factory:

database/factories/OrderFactory.php

class OrderFactory extends Factory
{
public function definition(): array
{
return [
'user_id' => User::factory(),
'name' => $this->faker->words(3, true),
'description' => $this->faker->paragraph(),
'date' => $this->faker->date,
'status' => $this->faker->randomElement(['P', 'F', 'C']),
// F = fulfilled, P = pending, C = canceled
];
}
}

So, you need to write a comment to others, to explain what those letters mean?

But what if that other developer finds those letters NOT in the Factory but somewhere else?

Here are the fragments from two FormRequest classes:

app/Http/Requests/Api/V1/StoreOrderRequest.php

'data.attributes.status' => 'required|string|in:P,F,C',

app/Http/Requests/Api/V1/UpdateOrderRequest.php

'data.attributes.status' => 'required|string|in:P,F,C',

No comments here on what those letters mean?

Also, in the Tests:

tests/Feature/OrderCreateTest.php

public function test_create_order_successfully()
{
// Define payload for the new order
$orderData = [
'data' => [
'attributes' => [
'user_id' => $user->id,
'name' => 'Test Order',
'description' => 'Test Order Description',
'status' => 'P',
'date' => now()->toDateString(),
],
],
];

What's that 'P', again?

A better way is to introduce a PHP Enum class.


Generate Enum

So, we run the Terminal command:

php artisan make:enum Enums/OrderStatus --string

Inside, we can leave the...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 09 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.