In this tutorial, you will learn how to create and manage routes in Laravel, a popular PHP framework used for web application development.
By the end of this tutorial, you will understand what routes are, how to create and manage them, and how they work in Laravel.
Before you start, you should have a basic understanding of PHP and a local Laravel installation on your machine. Laravel makes use of Composer, so it is recommended you have that installed as well.
Routes in Laravel are found in the routes
directory. The routes defined in web.php
are web routes that are assigned the web
middleware group.
To define a route, you simply need to match a URL with a Closure or controller action. Here's what a basic route might look like:
Route::get('/greeting', function () {
return 'Hello World';
});
In this example, we're defining a route that responds to HTTP GET requests on the /greeting
URL.
Here's an example of a basic GET route. When a user accesses the /greeting
URL, they will see "Hello World".
// This is a comment explaining the route.
Route::get('/greeting', function () {
// This closure returns the response that the user will see.
return 'Hello World';
});
You can also direct a route to a controller action. Here's an example of directing a GET request to the show
method of PostController
.
Route::get('/post', 'PostController@show');
In this example, when a user accesses the /post
URL, the show
method in PostController
will be executed.
Routes can also have parameters. Here's an example of a route with a parameter:
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
In this example, when a user accesses the /user/1
URL, they will see "User 1".
In this tutorial, we covered the basics of creating and managing routes in Laravel. We saw how to define a basic route, how to direct a route to a controller action, and how to use route parameters.
For further learning, you can explore more complex routing scenarios such as optional parameters, regular expression constraints, and named routes.
/about
URL and simply returns "About Us".Solution:
php
Route::get('/about', function () {
return 'About Us';
});
/contact
URL to the display
method of ContactController
.Solution:
php
Route::get('/contact', 'ContactController@display');
/product/{id}
URL and returns "Product " followed by the id.Solution:
php
Route::get('/product/{id}', function ($id) {
return 'Product '.$id;
});