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

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ử,

GitHub Actions CI/CD: quy trình deploy website an toàn

Hướng dẫn xây pipeline GitHub Actions CI/CD cho website: build, test, cache dependency, đóng artifact, deploy staging/production và quản lý secret an toàn.

.gitignore không hoạt động: nguyên nhân và cách sửa

Bài viết giúp bạn kiểm tra vì sao .gitignore không hoạt động, sửa lỗi file đã tracked và dùng git check-ignore để debug pattern.

Git push bị rejected: cách sửa non-fast-forward

Bài viết giải thích vì sao git push bị rejected, cách đọc lỗi non-fast-forward và quy trình xử lý an toàn trước khi push lại.

Git reset revert restore: chọn lệnh đúng

Bài viết so sánh git reset, git revert và git restore theo mục đích sử dụng: sửa staging area, khôi phục file, undo commit chưa push

Git commit vào nhánh sai: cách chuyển an toàn

Bài viết hướng dẫn xử lý git commit vào nhánh sai theo từng tình huống: commit chưa push, đã push, nhiều commit liên tiếp hoặc branch

TypeScript cho website doanh nghiệp: API, form và lỗi

TypeScript cho website doanh nghiệp đáng dùng khi bạn cần kiểm soát API contract, form schema, CMS payload và cấu hình môi trường. Bài này giúp