Learning Management Platform for Written Tutorial Series.

Laravel 5 Routing

Laravel 5 Routing

Introduction

In this tutorial, we are going to look at how routing works in Laravel 5.3.*. After that, we will implement the routes for our admin panel.

By the time that you are done with this tutorial, you will be familiar with the basics of routing in Laravel 5.3.* and how to apply the knowledge in a real-world project.

Laravel Routes

Topics to be covered

In this tutorial, we will cover the following topics;

  • Tutorial pre-requisites
  • Tutorial starter code
  • Laravel routing basics
  • Laravel advanced routing
  • Laravel routing best practices
  • Larashop admin panel routes
  • Tutorial complete code

Tutorial pre-requisites

This tutorial assumes;

  • You understand the basics of Laravel 5. If you do then I recommend you start with these Laravel 5 Tutorial series.
  • You have PHP, MySQL and a web server i.e. Apache up and running
  • Laravel Homestead – this is optional but provides a great development environment. If you are new to Laravel homestead then I recommend you read the series on Laravel Homestead
  • You have composer installed
  • You have a text editor or IDE that supports PHP.
  • You have a modern web browser that supports HTML5
  • Git – this is optional but highly recommended. This tutorial has a repository on GitHub, with Git, you will be able to clone starter code for each tutorial.

Tutorial starter code

This tutorial builds on from the previous tutorial. If you have not been following the tutorial series, then you can download starter code for this tutorial from GitHub

If you have git installed, run the following command to clone the project

git clone -b 01_starter https://github.com/KodeBlog/Laradmin.git laradmin

HERE,

  • git clone -b 01_starter clones the branch laradmin from the repository https://github.com/KodeBlog/Laradmin.git into a local folder laradmin.

Laravel routing basics

Routes provides the gateway into the application. Http verbs can be used to specify an action that the route should perform when called. For example, a GET http verb is used to retrieve resources while POST http verb is used to create a resource. Other commonly used routes are DELETE for deleting resources and PUT for updating existing resources.

Laravel provides support for all of the above http verbs and many more.

Routes in Laravel 5.3.* are located in routes directory. Laravel has three (3) categories namely

  • api.php – used to define routes for Application Programming Interface (APIs).
  • console.php – used to define routes for the command line
  • web.php – used to define routes for the web application.

Laravel runs different middleware on all of the above routes.

Run the following artisan command to see the middleware that is run on each route category

php artisan route:list

Laravel Routes

As you can see from the above results, the route / runs the web middleware by default while the route api/user runs the api, and auth:api middlware.

Let’s look at an example route

Open /routes/web.php

Route::get('/', function () {
    return view('welcome');
});

HERE,

  • The above route / responds to home page request. It uses an anonymous function and returns a view named welcome. This is useful for serving static pages.

Route parameters

You can also pass parameters to a route. Let’s look at how you can do that. Consider the following code

Route::get('/page/{name}', function ($name) {
    return "you requested for the page $name";
});

HERE,

  • Route::get('/page/{name}', function ($name) {…} defines a parameter {name} that we are passing in as a variable $name to the route anonymous function.

Making the following request http://localhost:8888/page/medusa returns the following result

you requested for the page medusa

Optional parameters

Using our above example, let’s say we want to return a default page if the user does not request a specific page. The sinful way of doing this would be to define two routes as follows

Route::get('/page', function ($name) {
    return "you requested for the default page";
});

Route::get('/page/{name}', function ($name) {
    return "you requested for the page $name";
});

The above code works just fine but what if we can define only a single route that handles both situations? This is where optional parameters come in handy. The above code can be re-factored as follows

Route::get('/page/{name?}', function ($name = "default") {
    return "you requested for the page $name";
});

HERE,

  • {name?} the question mark tells Laravel that this is an optional parameter. $name = "default" specifies the default value that will be used if no parameter value has been passed.

Laravel advanced routing

Now that we have covered the basics of routing, let’s look at some of the more advanced features of Laravel routing.

Regular expressions

Regular expressions allow us to put constraints on route parameters. For example, let’s suppose that you are creating a to-do app and you retrieve tasks based on the task id as a URL parameter. You can use a regular expression to restrict the acceptable parameter data type.

One of the advanced of using regular expressions on routes is improved security. For example, matching routes to only numeric parameters already prevents attacks such as SQL Injection. Any malicious code injected via the parameter is automatically ignored.

Let’s consider the following route

Route::get('/task/{id}', function($id){
    return "you requested for the task with id $id";
})->where('id', '[0-9]+');

HERE,

  • (...)->where('id', '[0-9]+'); put a restriction on the parameter id to accept only numeric values.

Named routes

As the name implies, named routes allow us to set a name for the route. Let’s look at an example before we look at the advantages of named routes.

Route::get('/task/{id}', function($id){
    return "you requested for the task with id $id. the current url is " . route('task',['id' => 1]);
})->where('id', '[0-9]+')->name('task');

HERE,

  • (...)->name('task'); sets task as the name of the route.
  • route('task',['id' => 1]) outputs the URL for the route named task. ['id' => 1] sets the value of the URL parameter id.

Run the following artisan command to list all the URLs for our project.

php artisan route:list

You will get the following results

Laravel Routes

Notice the task route is named task.

Named routes have the following two major advantages

Simplifies writing links. Instead of specifying the full URL path when redirecting or creating links in views, you simply use the route helper and specific the name of the route that you want. • Simplifies the process of updating URL. If you change the structure of your URLs, you only need to update the routes/web.php file. Your controllers and views with links to the named routes remain the same.

Grouped routes

Grouped routes allow us to write concise route code. Let’s suppose you are writing routes for the admin panel and you would like them to all start with admin. You can do that using the code below

Route::group(['prefix' => 'admin'],function()
{
    Route::get('/', function(){
        return "admin login/dashboard page";
    });

    Route::get('/departments', function(){
        return "departments page";
    });

    Route::get('/employees', function(){
        return "employees page";
    });
});

HERE,

  • Route::group(['prefix' => 'admin'],function(){…} defines a route group with a prefix of admin.
  • Route::get('/', function(){…}, Route::get('/departments', function(){…} defines routes that will be prefixed with admin. The above code will give us the routes http://localhost:8888/admin and http://localhost:8888/admin/employees respectively. Notice how we did not have to specify admin prefix for both URLs. You can also specify middleware on the route.

Route middleware

In a nutshell, middleware is simply a function that is run before or after the route has been processed. Let’s consider a practical example. All admin pages with the exception of login and log out need to be authenticated. We can easily check if the user is logged in by specifying the authentication middleware on the routes. Consider the following code

Route::group(['prefix' => 'admin','middleware' => 'auth'],function()
{
    Route::get('/departments', function(){
        return "departments page";
    });

    Route::get('/employees', function(){
        return "employees page";
    });
});

HERE,

  • 'middleware' => 'auth' assigns the authentication middleware to our routes. If the user is not signed in, the middleware will redirect them to the login page. If they are already signed in, the requested resource will be made available.

Laravel route namespace

By default, Laravel uses the App\Http\Controllers namespace in routes. This allows you to just specify the name of the controller without specifying the qualified namespace name such as \ App\Http\Controllers\HomeController. You can simply use HomeController and it will work just fine.

Laravel routing best practices

The following are some of the best practices that will make your life easier.

  • Take advantage of route groups when necessary. This will make your code cleaner and easy to update within the shortest possible time.
  • If you have repetitive code that you must run in the controllers such as checking if a user can perform a certain action, you can create middleware that does that and assign it on the routes.
  • Take advantage of named routes. This makes redirecting and creating navigation links super easy.
  • RESTful URLs are righteous – avoid creating URLs such as /list-products, /create-product, /update-product, /delete-product etc. instead use something products/create, products/edit/{id} etc. We will look at a practical example of how to achieve this as we proceed in the tutorial series.

Larashop admin panel routes

Now that we have covered some of the basic and advanced featured of Laravel routing, let’s define the routes for our admin panel. We will also create controllers for our routes.

Run the following artisan commands to create the routes for our categories

php artisan make:controller Admin\BrandsController --resource
php artisan make:controller Admin\ProductCategoriesController --resource
php artisan make:controller Admin\CustomersController --resource
php artisan make:controller Admin\OrdersController
php artisan make:controller Admin\ProductsController --resource
php artisan make:controller Admin\UsersController –resource

HERE,

  • Admin\* creates the controllers in the Admin directory of the Controllers directory with the following namespace namespace Larashop\Http\Controllers\Admin;
  • --resource generates a resource controller. A resource controller has boiler plate code for Create, Read, Update and Delete (CRUD) methods.

If you check the directory \app\Http\Controllers\Admin, you will be able to see the above controllers.

We will now update our web routes

Open web/routes.php

Update the routes as follows

Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function () {
    Route::resource('customers', 'CustomersController');
    Route::resource('brands', 'BrandsController');
    Route::resource('product-categories', 'ProductCategoriesController');
    Route::resource('products', 'ProductsController');
    Route::resource('users', 'UsersController');

    Route::get('orders', [
        'uses' => 'OrdersController@index',
        'as' => 'orders.index',
    ]);
});

HERE,

  • Route::group(…) defines the route group for our admin URLs
  • 'prefix' => 'admin' prefixes all of our routes with admin
  • 'namespace' => 'Admin' tells Laravel that our controllers for the group routes are in the Admin namespace. Admin will be appended to the default namespace and the qualified namespace will be Larashop\Http\Controllers\Admin. This will allows us to use only controller names when linking routes to controllers.
  • Route::resource('customers', 'CustomersController'); defines a resource controller customers and matches all the auto generated URLS to the resource methods in CustomersController.

Let’s now use artisan to view our routes. Open the command prompt / terminal and run the following command.

php artisan route:list

You will get the following beautiful table

Laravel Routes

As you can see from the above results, resource routes are automatically assigned a route name.

Tutorial Complete Code

The complete code for this tutorial can be cloned from the following branch

git clone -b 02_routes https://github.com/KodeBlog/Laradmin.git laradmin

Run the following command to browser to the root of the project

cd laradmin

We will now use composer to install dependencies.

composer install

When the installation is completed, run the following artisan command

php artisan serve

Summary

In this tutorial, we looked routing in Laravel, how it works and what are some of the advanced features available. We also looked at some of the best practices and created the routes for our tutorial project Laravel Admin Panel.

What’s next?

In the next tutorial, we will look at views. We will use Laravel blade template and implement the logic that displays the necessary views.

Kode Blog Tutorials is dedicated to bring you update to date, high quality free tutorials. You can support us by using the social media buttons to like and share the tutorial and subscribing to our newsletter. Please use the comments section below to give us feedback.

You can sign up for a free account on our site and you will be able to keep track of your progress as you go through the tutorial series and get notifications when we publish new content.


...