This section presents common enterprise scenarios formatted as Jira tickets. Each case includes the business requirement, technical constraints, and a senior-level implementation strategy.
The admin dashboard takes 8 seconds to load. Debugbar shows 150+ database queries. This is happening because we are iterating over 50 users and fetching their latest order individually.
- Reduce query count to < 5.
- Load time < 500ms.
👨💻 Senior Developer Solution
Strategy: This is a classic N+1 problem. We need to Eager Load the relationships using `with()`.
// ❌ Bad Code (N+1)
$users = User::all();
foreach ($users as $user) {
echo $user->latestOrder->total; // Triggers 1 query per user
}
// ✅ Good Code (Eager Loading)
$users = User::with('latestOrder')->get(); // 2 Queries total
foreach ($users as $user) {
echo $user->latestOrder->total; // No extra queries
}
Key Takeaway: Always use `with()` when you know you will access the relationship data.
Users are clicking "Generate Monthly Report" and the browser spins for 30 seconds until it times out. We need to make this asynchronous.
- User clicks button -> gets "Report processing started" message immediately.
- Report generates in background.
- User receives email when done.
👨💻 Senior Developer Solution
Strategy: Dispatch a Job to a Queue (Redis/Database) and return a response immediately.
// Controller
public function store() {
GenerateReportJob::dispatch(auth()->user());
return back()->with('status', 'Report is generating in the background!');
}
// Job Class
class GenerateReportJob implements ShouldQueue {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function handle() {
// Heavy processing...
$path = ReportService::generate($this->user);
// Notify user
Mail::to($this->user)->send(new ReportReady($path));
}
}
Key Takeaway: Never block the web request for tasks that take longer than 1-2 seconds.
The `OrderController::store` method is 400 lines long. It handles validation, payment processing, inventory updates, and email notifications. It's impossible to test.
- Extract business logic to a Service class.
- Controller should only handle HTTP request/response.
👨💻 Senior Developer Solution
Strategy: Implement the Service Pattern. Move logic to `OrderService`.
// OrderController.php
public function store(OrderRequest $request, OrderService $service) {
$order = $service->createOrder($request->validated(), auth()->user());
return redirect()->route('orders.show', $order);
}
// OrderService.php
class OrderService {
public function createOrder(array $data, User $user) {
DB::transaction(function() use ($data, $user) {
$order = Order::create([...]);
PaymentGateway::charge($user, $data['amount']);
Inventory::decrement($data['product_id']);
// ...
});
return $order;
}
}
Key Takeaway: Controllers should be skinny. Services contain the business logic and can be reused (e.g., by an API controller or CLI command).