How to Create Route in Laravel: Simple Guide
In Laravel, you create a route by adding it to the
routes/web.php file using the Route::get() or other HTTP verb methods. Each route defines a URL path and a callback or controller action that runs when the path is visited.Syntax
Laravel routes are defined in the routes/web.php file for web routes. The basic syntax uses the Route::method('uri', callback) pattern, where method is HTTP verbs like get, post, etc.
- Route::get: Defines a route that responds to GET requests.
- uri: The URL path to match.
- callback: A closure function or controller method to handle the request.
php
Route::get('/hello', function () { return 'Hello, Laravel!'; });
Example
This example shows a route that listens to the URL /greet and returns a simple greeting message. It demonstrates how to define a GET route with a closure callback.
php
<?php use Illuminate\Support\Facades\Route; Route::get('/greet', function () { return 'Welcome to Laravel routing!'; });
Output
When you visit http://your-app.test/greet in your browser, you will see: Welcome to Laravel routing!
Common Pitfalls
Common mistakes when creating routes include:
- Forgetting to import the
Routefacade withuse Illuminate\Support\Facades\Route;. - Defining routes outside the
routes/web.phpfile without proper setup. - Using the wrong HTTP method for the request type.
- Not returning a response from the route callback.
Here is an example of a wrong and right way:
php
<?php // Wrong: Missing Route facade import and no return Route::get('/wrong', function () { echo 'This will not work properly'; }); // Right: Proper import and return use Illuminate\Support\Facades\Route; Route::get('/right', function () { return 'This works correctly'; });
Quick Reference
| Method | Description | Example |
|---|---|---|
| Route::get | Handles GET requests | Route::get('/home', fn() => 'Home'); |
| Route::post | Handles POST requests | Route::post('/submit', fn() => 'Submitted'); |
| Route::put | Handles PUT requests | Route::put('/update', fn() => 'Updated'); |
| Route::delete | Handles DELETE requests | Route::delete('/delete', fn() => 'Deleted'); |
| Route::any | Handles any HTTP method | Route::any('/all', fn() => 'Any method'); |
Key Takeaways
Define routes in routes/web.php using Route facade methods like Route::get or Route::post.
Each route needs a URI and a callback that returns a response.
Always import the Route facade to avoid errors.
Match the HTTP method in your route to the type of request you expect.
Return a response from your route callback instead of echoing output.