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

Vibe coding và nợ kỹ thuật thầm lặng: kiểm soát bằng kỹ thuật ngữ cảnh

Vibe coding tăng tốc nhưng âm thầm tích lũy nợ kỹ thuật. Bài này giải thích vì sao và cách context engineering giúp bạn giữ codebase

Git stash: lưu tạm công việc dở và khôi phục đúng lúc

Git stash cho phép lưu tạm các thay đổi chưa commit để chuyển sang task khác, rồi khôi phục lại đúng lúc — tránh commit dở

Git rebase bị conflict: cách sửa hoặc abort an toàn

Hướng dẫn xử lý git rebase bị conflict: cách kiểm tra file lỗi, sửa conflict marker, tiếp tục rebase, abort an toàn và khi nào không

Bảo mật vibe coding: đừng để AI sinh lỗ hổng website

Bảo mật vibe coding không chỉ là quét lỗi sau khi AI viết code. Bài viết đưa ra checklist kiểm soát secret, prompt injection, dependency, auth

Kiểm thử code do AI tạo: danh sách kiểm tra trước khi deploy

Code do AI tạo cần được kiểm thử theo nhiều lớp trước khi lên website thật. Checklist này giúp bạn kiểm tra chức năng, bảo mật,

Lỡ push .env lên Git: cách xử lý secret bị lộ

Lỡ push .env lên Git không chỉ là lỗi xóa file. Hãy revoke hoặc rotate secret trước, rồi dọn Git history và ngăn sự cố lặp

Quy trình vibe coding 7 bước: từ ý tưởng đến prototype

Quy trình vibe coding hiệu quả bắt đầu từ giả thuyết kinh doanh, không phải prompt dài. Bài viết hướng dẫn 7 bước từ brief, dữ

Vibe coding cho doanh nghiệp: việc nào nên làm bằng AI?

Vibe coding cho doanh nghiệp hữu ích khi cần thử prototype, dashboard hoặc automation nhỏ. Bài viết giúp bạn phân loại use case theo mức rủi

AI viết code nhanh hơn review: kiểm soát thế nào?

Khi AI viết code nhanh hơn khả năng review của team, doanh nghiệp cần đổi cách kiểm soát chất lượng. Bài viết đưa ra framework thực

Git detached HEAD là gì? Cách thoát an toàn

Bài viết này giải thích detached HEAD trong Git, cách nhận biết trạng thái này và các bước thoát ra an toàn mà không mất code.

Rủi ro vibe coding: 9 lỗi khiến prototype khó vận hành

Bài viết này chỉ ra 9 rủi ro phổ biến khi vibe coding và cách kiểm soát để prototype không biến thành gánh nặng vận hành.

Vibe coding là gì? Cách thử ý tưởng phần mềm bằng AI

Vibe coding giúp chủ doanh nghiệp biến ý tưởng phần mềm thành prototype nhanh hơn bằng AI. Bài viết này chỉ ra khi nào nên thử,