Controller gom các xử lý liên quan vào một lớp, giúp routes gọn gàng. Bài này tạo controller, nhận dữ liệu từ Request và trả về view, JSON hoặc chuyển hướng.

40 phútTrung cấp
Bạn sẽ học được
  • Tạo controller
  • Nhận Request
  • Trả view, JSON, redirect
  • Dependency Injection trong controller

Cơ sở lý thuyết

Controller nhận yêu cầu đã được router chuyển tới, điều phối việc lấy dữ liệu (Model) và chọn cách phản hồi (View, JSON, chuyển hướng). Nguyên tắc controller mỏng: controller chỉ điều phối, nghiệp vụ phức tạp đặt ở Model hoặc lớp Service.

  • Đối tượng Request đóng gói mọi thông tin yêu cầu: tham số truy vấn, dữ liệu form, tệp, header, người dùng hiện tại.
  • Route model binding: Laravel tự truy vấn bản ghi theo tham số URL; không tìm thấy thì trả 404.
  • Dependency Injection: khai báo kiểu tham số (Request, Service) trong hàm, service container tự tạo và truyền vào.
  • Mẫu Post/Redirect/Get: sau khi xử lý form POST thì chuyển hướng sang trang GET, tránh gửi lại form khi người dùng tải lại trang.

Ví dụ

namespace App\Http\Controllers;

use App\Models\SinhVien;
use Illuminate\Http\Request;

class SinhVienController extends Controller
{
    public function index(Request $request)
    {
        $tuKhoa = $request->query('q');
        $ds = SinhVien::when($tuKhoa, fn ($q) => $q->where('ten', 'like', "%$tuKhoa%"))
                      ->orderBy('ten')->paginate(10);
        return view('sinhvien.index', compact('ds', 'tuKhoa'));
    }

    public function show(SinhVien $sinhvien)          // route model binding
    {
        return view('sinhvien.show', ['sv' => $sinhvien]);
    }

    public function apiDanhSach()
    {
        return response()->json(SinhVien::all());
    }
}

Route model binding: Laravel tự tìm bản ghi theo id trên URL, trả 404 nếu không có.

Ứng dụng thực tế

Bài toán: trang danh sách sinh viên có tìm kiếm, lọc theo lớp, sắp xếp và giữ nguyên điều kiện lọc khi chuyển trang – yêu cầu thường gặp của mọi trang quản trị:

public function index(Request $request)
{
    $ds = SinhVien::query()
        ->with('lop')
        ->when($request->filled('q'), fn ($q) => $q->where('ten', 'like', '%' . $request->q . '%'))
        ->when($request->filled('lop'), fn ($q) => $q->where('lop_id', $request->lop))
        ->orderBy($request->input('sap_xep', 'ten'))
        ->paginate(20)
        ->withQueryString();                          // giữ ?q=...&lop=... trên liên kết phân trang
    return view('sinhvien.index', ['ds' => $ds, 'dsLop' => Lop::orderBy('ten')->get()]);
}
Thực hành
  1. Tạo controller trang chủ trả về view.
  2. Viết action tìm kiếm theo từ khóa.
  3. Viết action trả về JSON.
Tóm tắt bài học
  • Controller gom xử lý theo chức năng.
  • Request chứa dữ liệu người dùng gửi.
  • Route model binding tự tìm bản ghi.