Back to Publication
Laravel & PHP
By Riazul Islam•
Summary: Laravel is opinionated for a reason. Here are 10 tips that transformed how I write PHP code - from messy scripts to elegant applications.
## Laravel Taught Me How to Write Clean Code
Before Laravel, my PHP code was spaghetti. Laravel forced me to think about structure, patterns, and elegance. Here are the tips that made the biggest difference.
### 1. Use Eloquent Relationships Properly
```php
// Instead of raw queries
$orders = DB::select("SELECT * FROM orders WHERE user_id = ?", [$userId]);
// Use Eloquent relationships
$orders = $user->orders()->with("items")->latest()->get();
```
### 2. Form Request Validation
Move validation out of controllers:
```php
class StoreUserRequest extends FormRequest
{
public function rules()
{
return [
"name" => "required|string|max:255",
"email" => "required|email|unique:users",
];
}
}
```
### 3. Use Queues for Heavy Tasks
Sending emails, processing images, generating reports - put them in a queue:
```php
SendWelcomeEmail::dispatch($user);
```
### 4. Repository Pattern for Complex Queries
Keep controllers thin, models clean:
```php
class UserRepository
{
public function getActiveWithOrders()
{
return User::active()->with("orders")->get();
}
}
```
### 5. Use Laravel Collections
Collections are incredibly powerful:
```php
$topCustomers = $orders
->groupBy("user_id")
->map->sum("total")
->sortDesc()
->take(10);
```
### 6. API Resources for Response Formatting
Never return raw models from APIs:
```php
return UserResource::collection($users);
```
### 7. Use Observers for Side Effects
```php
class OrderObserver
{
public function created(Order $order)
{
$order->user->notify(new OrderConfirmation($order));
}
}
```
### 8. Cache Expensive Queries
```php
$stats = Cache::remember("dashboard-stats", 3600, function () {
return $this->calculateStats();
});
```
### 9. Use Enums (PHP 8.1+)
```php
enum OrderStatus: string
{
case Pending = "pending";
case Processing = "processing";
case Shipped = "shipped";
}
```
### 10. Write Tests
```php
public function test_user_can_place_order()
{
$user = User::factory()->create();
$response = $this->actingAs($user)
->post("/orders", $this->validOrderData());
$response->assertStatus(201);
}
```
**Laravel isn't just a framework. It's a way of thinking about software.**
