Chapter 3. Routing and Controllers
The essential function of any web application framework is to take requests from a user and deliver responses, usually via HTTP(S). This means defining an application’s routes is the first and most important project to tackle when learning a web framework; without routes, you have no ability to interact with the end user.
In this chapter we will examine routes in Laravel and show how to define them, how to point them to the code they should execute, and how to use Laravel’s routing tools to handle a diverse array of routing needs.
Route Definitions
In a Laravel application, you will define your “web” routes in routes/web.php and your “API” routes in routes/api.php. Web routes are those that will be visited by your end users; API routes are those for your API, if you have one. For now, we’ll primarily focus on the routes in routes/web.php.
Note
In projects running versions of Laravel prior to 5.3, there will be only one routes file, located at app/Http/routes.php.
The simplest way to define a route is to match a path (e.g., /) with a closure, as seen in Example 3-1.
Example 3-1. Basic route definition
// routes/web.phpRoute::get('/',function(){return'Hello, World!';});
You’ve now defined that, if anyone visits ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access