Laravel Basic Routing: web.php and Closures
When someone types yourshop.in/about into a browser, something has to decide what happens next. Which code should run? What should the user see? In Core PHP, the answer was a file: about.php simply existed on the server, and the URL matched the filename.
Laravel works differently. Every request enters through public/index.php, as you saw in the Request Lifecycle lesson, so Laravel needs its own way to decide what to do with each URL. That mechanism is routing. A route is a simple instruction: “when a request arrives for this URL with this HTTP method, run this code.”
In this lesson, you will write your first routes, return different kinds of responses, and learn the errors beginners hit most often. Parameters, named routes, groups and controllers each get their own lesson later in the chapter.
What Is a Route?
A route connects two things:
- A URL (like
/about) combined with an HTTP method (like GET) - The code that should run when that request arrives
Here is the simplest possible route:
Route::get('/about', function () {
return 'About MasterShop';
});
Read it like a sentence: “When a GET request arrives for /about, run this function and send back whatever it returns.” The function is called a closure, which is just an anonymous function you pass directly into the route. Each route is a small, complete instruction.
Where Routes Live: routes/web.php
All your route files live in the routes/ folder. In a fresh Laravel 13 project, the file you will use most is routes/web.php, which holds the routes for your website’s pages. Open it and you will see the default welcome page route:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Two things are worth noticing:
- The
useline at the top imports theRoutefacade. Without it,Route::get()would not work. - Routes in
web.phpautomatically get the web middleware group, which gives you session state and CSRF protection. You do not have to turn these on.
You may wonder how Laravel even knows this file exists. It is loaded from bootstrap/app.php, which you have already seen:
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
//
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();
The web: line tells Laravel where your web routes are. The health: '/up' line gives you a built-in health check URL, which is useful later when you deploy.
There is no routes/api.php in a new project. It is added only when you need an API, using php artisan install:api, and you will do that in the REST API chapter.
Your First Routes
Start your development server, as you learned in the installation lesson:
php artisan serve
Now add these routes to routes/web.php:
Route::get('/hello', function () {
return 'Hello from Laravel!';
});
Route::get('/about', function () {
return 'About MasterShop';
});
Route::get('/contact', function () {
return 'Contact us at [email protected]';
});
Visit http://127.0.0.1:8000/hello, /about and /contact in your browser. Each URL shows its own text. You just built three pages without creating a single file per page.
Laravel picks up changes to routes/web.php immediately. You do not need to restart the server after editing a route.
What a Route Can Return
A closure can return different kinds of things, and Laravel turns each one into a proper HTTP response.
A string is sent as plain text or HTML:
Route::get('/welcome-text', function () {
return '<h1>Welcome to MasterShop</h1>';
});
An array is automatically converted to JSON:
Route::get('/status', function () {
return [
'shop' => 'MasterShop',
'open' => true,
'orders' => 42,
];
});
Visit /status and your browser shows {"shop":"MasterShop","open":true,"orders":42} as JSON. This is handy for quick API-style responses.
A view renders a Blade template from resources/views/:
Route::get('/home', function () {
return view('home');
});
This looks for resources/views/home.blade.php. Views get a full chapter later, so for now just know that this is how routes display real pages.
An explicit JSON response gives you more control, such as setting a status code:
Route::get('/error-demo', function () {
return response()->json(['message' => 'Something went wrong'], 500);
});
The second argument is the HTTP status code. The full story of responses is covered in the Requests, Responses & Middleware chapter.
HTTP Verbs: GET, POST, PUT, PATCH, DELETE
So far, every route used Route::get(). The router supports every common HTTP verb, and each one signals a different intention:
Route::get('/invoices', function () {
return 'List of invoices';
});
Route::post('/invoices', function () {
return 'Create a new invoice';
});
Route::put('/invoices', function () {
return 'Replace an invoice';
});
Route::patch('/invoices', function () {
return 'Update part of an invoice';
});
Route::delete('/invoices', function () {
return 'Delete an invoice';
});
Here is what each verb is meant for:
- GET: read or display something. Visiting a page in the browser is a GET request.
- POST: create something new, such as submitting a form.
- PUT: replace an existing record completely.
- PATCH: update only some fields of an existing record.
- DELETE: remove a record.
Notice that all five routes above use the same URL. Laravel tells them apart by the HTTP method. This is the foundation of how clean applications and APIs are structured.
There is one catch while learning: your browser’s address bar can only send GET requests. If you visit /invoices, you will see “List of invoices”, but you cannot trigger the POST or DELETE routes just by typing a URL. They are triggered by HTML forms (covered in the Forms & Validation chapter) or by API tools like Postman (covered in the REST API chapter).
Matching More Than One Verb
Sometimes one route needs to respond to several verbs. Use match for a specific list, or any for all of them:
Route::match(['get', 'post'], '/feedback', function () {
return 'Feedback page';
});
Route::any('/ping', function () {
return 'pong';
});
These are useful in rare cases, such as a page that shows a form on GET and processes it on POST. In most projects, you will define separate routes per verb.
Injecting Dependencies into a Closure
Remember the Service Container from the previous lesson? It works inside route closures too. If you type-hint a class in the closure’s parameters, Laravel injects it automatically:
use Illuminate\Http\Request;
Route::get('/whoami', function (Request $request) {
return 'You made a ' . $request->method() . ' request to ' . $request->path();
});
Visit /whoami and you will see something like “You made a GET request to whoami”. The Request object holds everything about the incoming request. You will explore it fully in the Request Object lesson later.
Route Order and Duplicate Routes
Laravel stores routes by their HTTP method and URL. If you define the same URL with the same method twice, the later definition replaces the earlier one:
Route::get('/offers', function () {
return 'First version';
});
Route::get('/offers', function () {
return 'Second version';
});
Visiting /offers shows “Second version”. The first route is silently overwritten, and Laravel does not warn you.
This matters most when you mix any or match with specific verbs on the same URL:
// Wrong order: any() comes first and gets overwritten for GET
Route::any('/support', function () {
return 'Handles every verb';
});
Route::get('/support', function () {
return 'Handles GET only';
});
The safe habit, which the Laravel documentation recommends, is to define specific verbs (get, post, and so on) before any, match and redirect routes that share the same URL.
Closures vs Controllers
Closures are perfect for learning, quick tests, and tiny routes that return a simple response. But recall the MVC lesson: routes should point, not execute. Once a route needs real logic, such as database queries, validation or business rules, the closure turns into the “logic dump” you were warned about.
// Fine: simple and short
Route::get('/about', function () {
return view('about');
});
// Not fine: this belongs in a controller
Route::get('/orders', function () {
$orders = Order::where('status', 'paid')
->whereMonth('created_at', now()->month)
->with('customer')
->get();
// ...50 more lines of logic...
});
In the Controllers chapter, you will learn to replace closures with controller methods. Until then, closures are the quickest way to practise routing.
Checking Your Routes
As your project grows, you will want to see every route at once. Laravel gives you a command for it:
php artisan route:list
This prints each route with its method, URL and what handles it. Right now it is a handy sanity check that your new routes were registered. A later lesson in this chapter covers it in more detail, along with its useful options.
Common Mistakes
Mistake 1: Forgetting to Return
Route::get('/hello', function () {
'Hello from Laravel!'; // no return
});
The page loads, but it is blank. The closure ran, but nothing was returned, so Laravel has nothing to send. Always return the value.
Mistake 2: The 404 Not Found Error
If you visit a URL and see a “404 | NOT FOUND” page, Laravel found no route matching that URL and method. Check for typos in the URL and make sure the route is saved in routes/web.php. Remember that /about and /about-us are different routes.
Mistake 3: The 405 Method Not Allowed Error
The GET method is not supported for route invoices. Supported methods: POST.
The URL exists, but you used the wrong verb. This often happens when you define Route::post('/invoices', ...) and then visit /invoices in the browser, which sends GET. Either add a GET route for that URL or trigger the POST route through a form or API tool.
Mistake 4: The 419 Page Expired Error
If a form posts to a route in web.php and you see “419 | PAGE EXPIRED”, the request was missing a CSRF token. Routes in web.php are protected against Cross-Site Request Forgery, so any HTML form that sends POST, PUT, PATCH or DELETE must include @csrf. You will build forms properly in the Forms & Validation chapter.
Mistake 5: Defining the Same Route Twice
As shown above, a later route silently overrides an earlier one with the same method and URL. If a route behaves strangely, run php artisan route:list and check whether you defined it twice.
Mistake 6: Putting Heavy Logic Inside Closures
Closures that grow beyond a few lines are hard to read and impossible to reuse. If a closure needs a database query or a business rule, that is your signal to move it into a controller.
Quick Summary
- A route connects a URL and an HTTP method to the code that handles it.
- Web routes live in
routes/web.php, loaded throughbootstrap/app.php, and get the web middleware group (sessions and CSRF protection). - A closure is an anonymous function you pass directly to the route.
- A route can return a string, an array (converted to JSON), a view, or an explicit response.
- Use
Route::get,post,put,patchanddeletefor the five main verbs. The same URL can have different routes per verb. matchhandles a chosen list of verbs, andanyhandles all of them. Define specific verbs first.- Defining the same method and URL twice means the later route wins.
- Keep closures for simple routes and move real logic into controllers.
php artisan route:listshows every registered route.- 404 means no matching route, 405 means the wrong verb, and 419 means a missing CSRF token.
What’s Next
Right now, every URL in your app is fixed: /about is always /about. Real applications need dynamic URLs like /invoices/15 or /products/laptop, where part of the URL changes. In the next lesson, you will learn Route Parameters and Constraints, which let you capture values from the URL and control exactly what they are allowed to look like.