Laravel for Beginners: Routing and Controllers (Chapter 3)

Nội dung

In this article, we’ll be exploring the concept of routing and controllers in Laravel. Routing is the process of mapping URLs to specific actions, and controllers are the classes that handle these actions. Understanding routing and controllers is essential for building robust and scalable applications in Laravel.

Objectives The objectives of this article are to:

  • Explain the basics of routing in Laravel
  • Show how to define routes in Laravel
  • Discuss how to create controllers in Laravel
  • Demonstrate how to use controllers to handle requests in Laravel

Routing in Laravel

What is routing?

Routing is the process of mapping URLs to specific actions in your application. When a user visits a URL, the router matches the URL to a predefined action and returns the appropriate response.

Defining routes in Laravel

In Laravel, you can define routes in the routes/web.php file. By default, Laravel includes a few basic routes to get you started. For example, the following code defines a route for the home page of the application:

Route::get('/', function () {
    return view('welcome');
});

Available Route Methods

Laravel provides several methods for defining routes, including get, post, put, patch, and delete. These methods correspond to the HTTP methods and determine how the route can be accessed. For example, the following code defines a route that can only be accessed using the POST method:

Route::post('/contact', function () {
    // handle contact form submission
});

Controllers in Laravel

What are controllers?

Controllers are classes that handle requests and return responses in Laravel. In other words, controllers are responsible for processing incoming requests, executing business logic, and returning appropriate responses.

Creating Controllers

To create a controller in Laravel, you can use the Artisan command line tool. The following command creates a new controller called PageController:

php artisan make:controller PageController

Using Controllers

To use a controller in Laravel, you need to define a route that maps to a specific action in the controller. For example, the following code defines a route that maps to the index action in the PageController:

Route::get('/pages', 'PageController@index');

Returning Responses from Controllers

View Responses

In Laravel, you can return view responses from controllers using the view function. For example, the following code returns a view response from the index action in the PageController:

public function index()
{
    return view('pages.index');
}

JSON Responses

In addition to view responses, you can also return JSON responses from controllers. For example, the following code returns a JSON response from the index action in the PageController:

public function index()
{
    return response()->json([
        'message' => 'Welcome to the PageController index action'
    ]);
}

Conclusion

Recap of what was covered In this article, we covered the basics of routing and controllers in Laravel. We explained what routing is and how to define routes in Laravel. We also discussed what controllers are and how to create and use them to handle requests in Laravel. Additionally, we showed how to return both view and JSON responses from controllers.

Next steps Now that you have a solid understanding of routing and controllers in Laravel, you can start building more complex applications that handle a wide range of HTTP requests. Some next steps could include:

  • Learning how to pass data to views and controllers
  • Understanding middleware and how to use it to secure routes
  • Exploring advanced routing concepts, such as named routes and route groups

Summary Routing and controllers are key concepts in Laravel that enable you to handle HTTP requests and return appropriate responses. By understanding how to define routes, create controllers, and return responses, you’ll be able to build robust and scalable applications in Laravel.

Anthony Nguyễn

Cây bút chính tại VietnamTutor

Bài viết cùng chuyên mục

Nâng Cấp Laravel 13: Checklist 10 Bước Không Thể Bỏ Qua 2026

Hướng dẫn nâng cấp Laravel 13 chi tiết với checklist 10 bước. Từ kiểm tra PHP 8.3, cập nhật dependencies, đến xử lý lỗi thường gặp

Hardening Laravel Production: Checklist Bảo Mật Toàn Diện 2026

Checklist hardening Laravel production toàn diện. Từ cấu hình server, database, SSL đến security headers, rate limiting và monitoring.

Authentication & Authorization Trong Laravel: Hướng Dẫn A-Z 2026

Hướng dẫn chi tiết cách xây dựng hệ thống Authentication (xác thực) và Authorization (phân quyền) trong Laravel với Breeze, Fortify, Sanctum, Policies và Gates.

Bảo Mật Laravel: 10 Lỗi Phổ Biến & Cách Phòng 2026

Hướng dẫn 10 lỗi bảo mật phổ biến nhất trong Laravel và cách phòng tránh hiệu quả. Từ XSS, SQL injection đến authentication vulnerabilities.

Migration PHP Attributes Laravel 13: Hướng Dẫn Chi Tiết

Cách chuyển đổi từ protected properties sang PHP Attributes trong Laravel 13 với hướng dẫn từng bước và code examples chi tiết.

Laravel 13 Có Gì Mới? Tổng Hợp Tính Năng Mới 2026

Laravel 13 ra mắt ngày 17/3/2026 với PHP 8.3, PHP Attributes, AI SDK và nhiều cải tiến. Khám phá chi tiết các tính năng mới của

Kubernetes for Beginners 2026: Hướng Dẫn Từ A-Z

Kubernetes (K8s) là nền tảng container orchestration phổ biến nhất hiện nay. Bài hướng dẫn này sẽ giúp bạn hiểu Kubernetes là gì, kiến trúc cơ

Docker Compose Best Practices 2026: 10 Tips Quan Trọng

Docker Compose giúp bạn quản lý multi-container applications dễ dàng hơn. Bài viết này tổng hợp 10 best practices quan trọng nhất để sử dụng Docker

Lỗ hổng RCE (CVE-2025-55182) trên React, Next.js?

Cảnh báo khẩn cấp: React2Shell (CVE-2025-55182) gây RCE nghiêm trọng cho React/Next.js. Nắm cơ chế, dấu hiệu & phòng thủ cấp bách để bảo vệ ứng

Dead-Letter Queue: Giải pháp cứu cánh cho tin nhắn lỗi hệ thống

DLQ là chìa khóa quản lý tin nhắn lỗi hiệu quả trong hệ thống phân tán. Đảm bảo tin nhắn không bị mất, tăng độ tin

Lập trình viên: Xây doanh nghiệp một người, kiếm 10.000 USD/tháng

Lập trình viên: Khám phá khung làm việc để xây dựng doanh nghiệp một người, kiếm 10.000 USD/tháng. Biến kỹ năng code thành cỗ máy tiền,