Creating and Managing Routes

Tutorial 3 of 5

Creating and Managing Routes in Laravel

1. Introduction

Goal of the Tutorial

In this tutorial, you will learn how to create and manage routes in Laravel, a popular PHP framework used for web application development.

Learning Outcomes

By the end of this tutorial, you will understand what routes are, how to create and manage them, and how they work in Laravel.

Prerequisites

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.

2. Step-by-Step Guide

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.

3. Code Examples

Basic Route

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';
});

Route to Controller

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.

Route Parameters

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".

4. Summary

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.

5. Practice Exercises

  1. Exercise: Create a route that responds to a GET request on the /about URL and simply returns "About Us".

Solution:

php Route::get('/about', function () { return 'About Us'; });

  1. Exercise: Create a route that directs a GET request on the /contact URL to the display method of ContactController.

Solution:

php Route::get('/contact', 'ContactController@display');

  1. Exercise: Create a route with a parameter that responds to a GET request on the /product/{id} URL and returns "Product " followed by the id.

Solution:

php Route::get('/product/{id}', function ($id) { return 'Product '.$id; });