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

n8n public API rate limits: cấu hình và xử lý lỗi 429

Hướng dẫn vận hành giới hạn public API n8n trên self-host: bật theo API key, chọn ngưỡng đọc/ghi, theo dõi header và xử lý 429 mà

MCP Claude Code: kết nối công cụ và kiểm soát quyền

Hướng dẫn kết nối MCP trong Claude Code qua HTTP hoặc stdio, chọn cấu hình cá nhân hay chia sẻ với team, kiểm tra trạng thái

Claude Skills + Projects: xây quy trình AI tự vận hành

Hướng dẫn ghép prompt, Projects, Skills và scheduled tasks thành workflow Claude tự vận hành cho team dev và agency nhỏ.

Git status và git diff: cách xem file đã thay đổi

Hai lệnh cần chạy trước mọi commit: git status để biết file nào đang untracked, modified hay staged; git diff để xem nội dung thay đổi

Subagent Claude Code: chia việc cho agent phụ an toàn

Hướng dẫn dùng subagent trong Claude Code: tạo file agent trong .claude/agents, siết quyền bằng tools và permissionMode, cô lập bằng worktree, và chọn model để

Skills trong Claude Code: biến quy trình thành lệnh tái dùng

Hướng dẫn dùng skills trong Claude Code: cấu trúc SKILL.md, vị trí lưu cho cá nhân và team, kiểm soát ai được gọi skill, và các

Plan mode Claude Code: bắt AI lập kế hoạch trước khi viết code

Bài giải thích plan mode trong Claude Code: cách bật bằng Shift+Tab hoặc /plan, Claude được làm gì khi chỉ-đọc, checklist đọc plan trước khi duyệt,

Checkpoint trong Claude Code: quay lại khi AI sửa hỏng code

Bài giải thích cơ chế checkpoint của Claude Code, cách dùng /rewind để khôi phục code và hội thoại, những trường hợp checkpoint không cứu được,

Permission mode trong Claude Code: chọn mức quyền an toàn

Bài giải thích 6 permission mode của Claude Code, cách đổi chế độ bằng Shift+Tab và cờ khởi động, cùng nguyên tắc chọn mức quyền an

Sửa code bằng Claude Code: quy trình an toàn cho người mới

Bài hướng dẫn quy trình sửa code bằng Claude Code an toàn cho người mới: cách viết yêu cầu, duyệt quyền, kiểm tra thay đổi, kiểm

CLAUDE.md là gì? Cách ghi quy tắc dự án để Claude Code làm đúng

Bài giải thích CLAUDE.md là gì, file này load từ đâu, nên ghi nội dung nào và cách bảo trì để Claude Code làm đúng quy

7 lệnh Claude Code cần biết: /help, /clear, /compact và cách dùng

Bài hướng dẫn 7 lệnh Claude Code quan trọng nhất cho người mới bắt đầu, kèm ví dụ thực tế và thời điểm nên dùng từng