How to Use Route::get in Laravel for Simple Routing
In Laravel, use
Route::get to define a route that responds to HTTP GET requests by specifying the URL path and a callback or controller action. This method maps a URL to a function or controller method that returns a response when the route is accessed.Syntax
The Route::get method defines a route that listens for HTTP GET requests. It takes two main arguments: the URL path as a string, and a callback function or controller action that returns the response.
- URL path: The part of the URL after your domain, e.g.,
'/home'. - Callback or controller: A function or controller method that runs when the route is accessed.
php
Route::get('/url-path', function () { return 'Response content'; });
Example
This example shows how to create a simple route that returns a welcome message when the user visits the /welcome URL.
php
<?php use Illuminate\Support\Facades\Route; Route::get('/welcome', function () { return 'Welcome to Laravel!'; });
Output
When you visit http://your-app.test/welcome in a browser, you will see: Welcome to Laravel!
Common Pitfalls
Common mistakes when using Route::get include:
- Forgetting to import the
Routefacade withuse Illuminate\Support\Facades\Route;. - Not returning a response from the callback function, which causes an empty page.
- Using the wrong HTTP method (e.g.,
Route::postinstead ofRoute::get) for GET requests. - Defining routes with the same URL path multiple times, which causes conflicts.
Wrong example:
Route::get('/home', function () {
echo 'Hello'; // Using echo instead of return
});Right example:
Route::get('/home', function () {
return 'Hello';
});Quick Reference
Use Route::get to handle HTTP GET requests by specifying a URL and a callback or controller method. Always return a response from the callback. Import the Route facade at the top of your routes file.
| Part | Description |
|---|---|
| Route::get | Defines a route for HTTP GET requests |
| '/url-path' | The URL path to listen for |
| Callback function | Returns the response when the route is accessed |
| use Illuminate\Support\Facades\Route; | Import statement needed to use Route |
Key Takeaways
Use Route::get to define routes that respond to HTTP GET requests.
Always return a response from the callback function or controller method.
Import the Route facade before defining routes.
Avoid duplicate URL paths to prevent route conflicts.
Use Route::get for URLs that should display data or pages.