Courses

Laravel API Code Review and Refactor

Static String Letters to PHP Enum

You're reading a FREE PREVIEW of a PREMIUM course.

Link to the repository

[Only for premium members]

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 15 lessons of this course? (56 min read)

You also get:

  • 76 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord