Close

Tutorial Lengkap Controller Laravel untuk Pemula

Tutorial Laravel - Controller

Waktu membaca : 4 menit

Menciptakan “Slim Controller” (Controller Ramping)

Konsep utama dalam Memahami controller di laravel 12 adalah menghindari “Fat Controller” yang sarat dengan logika bisnis, validasi, dan manipulasi data. Controller seharusnya hanya menjadi perantara, bukan pekerja keras.

Delegasikan Logika Bisnis ke Service Class

Ini adalah best practice paling krusial. Alihkan logika bisnis yang kompleks (seperti kalkulasi harga, workflow multi-langkah, atau pemrosesan data) dari controller ke kelas khusus yang disebut Service Class (atau Action Class).

Contoh “Fat Controller” (❌ Bad Practice):

// app/Http/Controllers/OrderController.php (CONTOH BURUK!)
public function store(Request $request)
{
    // 1. Validasi
    $request->validate(['items' => 'required|array', 'total' => 'required|numeric']);

    // 2. Logika Bisnis (Hitung diskon, cek stok, dll.)
    $discount = $this->calculateDiscount($request->user());
    $total_price = $request->total - $discount;

    // 3. Interaksi Model (Menyimpan)
    $order = Order::create([... 'total' => $total_price]);

    // 4. Logika Bisnis Lain (Notifikasi)
    $this->sendNotification($order);

    return response()->json($order, 201);
}

Contoh “Slim Controller” (✅ Best Practice) dengan Service Layer:

// app/Services/OrderService.php (Service Class)
class OrderService
{
    public function createOrder(array $data, User $user)
    {
        // Semua logika bisnis, diskon, cek stok, dll. dilakukan di sini.
        // Kemudian, simpan ke database.
        // ...
    }
}

// app/Http/Controllers/OrderController.php
use App\Services\OrderService;
use App\Http\Requests\StoreOrderRequest; // Menggunakan Form Request untuk Validasi

public function store(StoreOrderRequest $request, OrderService $orderService) // Dependency Injection
{
    $order = $orderService->createOrder($request->validated(), $request->user()); // Murni mendelegasikan
    
    // Controller hanya menangani response
    return response()->json(['message' => 'Order berhasil dibuat', 'order' => $order], 201);
}

Dengan mengadopsi struktur ini, controller Anda menjadi tipis, hanya berfokus pada menerima Request dan mengembalikan Response. Logika bisnis menjadi mudah diuji karena terpisah dalam OrderService.

Leave a Reply

Your email address will not be published. Required fields are marked *

Leave a comment
scroll to top