Learning Management Platform for Written Tutorial Series.

Laravel 6 Routing

Laravel 6 Routing

Routing is the process of mapping URLs to methods that we define in our controllers. This can be a web or API route. Web routes respond to requests that come from web browsers. API routes respond to requests from APIs. Laravel also supports other kinds of routes like commands from the terminal and channels.

In this lesson, we will look at how we can handle routing in Laravel and through in a bit of some cool Search Engine Optimization (SEO) tips relative to routes.

Topics to be covered

We will cover the following topics in this lesson.

  • SEO Friendly URLs
  • Types of Routes
  • Named Routes
  • Route Parameters
  • Optional Parameters
  • Route Middleware
  • Redirecting

SEO Friendly URLs

SEO friendly URLs means URLs that users can easily understand and most importantly google will love and give us some of that free organic traffic. This isn't a lesson on SEO but an introduction to creating applications that will make SEO experts recommend your web applications.

Consider the following URLs

/page.php?pid=34
/create_customer

Sure the above URLs work but we can improve them like so

/page.php?page=about-us
/create-customer

HERE,

  • /page.php?page=about-us In the first URL, we replaced pid=34 with page=about-us which is more descriptive to both search engines and the user visiting the website.
  • /create-customer replaced the underscore _ with a dash - this makes it easier to read URLs for both human and search bots.

That's all the SEO we needed to know to get started creating SEO friendly URLs in Laravel.

Types of Routes

Laravel supports the following types of URLs. In this section, we will proceed working with the HelloWorld project that we created in the previous lesson.

Web Routes

Web routes respond to requests that come from web browsers. The file for web routes is located in /routes/web.php

Let's now create a simple web URL

Open /routes/web.php

Add the following code

Route::get('/about-us',function(){
    return 'About us page';
});

HERE,

  • Route::get('/about-us',function(){...} defines a route about-us that returns a simple text in the browser.

Run the following command to start the built-in server

php artisan serve

Once the development server has been started, you can load the following URL into your web browser

http://localhost:8000/about-us

You should be able to see the following results

About us page

We can also pass parameters to a route like so.

Route::get('/pages/{name}',function($name){
    return "$name page";
});

HERE,

  • Route::get('/pages/{name}',function($name){...} defines a route pages that accepts a parameter of name which we are passing as an argument to our anonymous function function($name). return "$name page"; prints the page name in the browser

Try loading the following URLs in your web browser

http://localhost:8000/pages/services
http://localhost:8000/pages/products
http://localhost:8000/pages/contact-us

API Routes

API standards for Application Programming Interface. API are used when more than one system need to communicate. For example, you can have a web application with ecommerce data and you create a mobile application that should have access to the data that is created in the website. You can use an API to do that.

By default, most APIs work with JSON. In this section, we will create a simple API route that returns a JSON object.

Open /routes/api.php

Add the following route

Route::get('/products', function() {
    $products = [
        [
            'name' => 'Macbook Pro',
            'price' => 2500
        ],
        [
            'name' => 'iPhone',
            'price' => 1200
        ]
    ];

    return response()->json($products);
});

HERE,

  • Route::get('/products', function() {...} defines an API route /products.
  • $products = [...] defines a multi-dimensional array that contains two products. This data usually comes from the database.
  • return response()->json($products); returns our array as a JSON object. We will talk more about creating APIs in future lessons.

Load the following URL in your browser

http://localhost:8000/api/products

You should be able to get the following results

[
   {
      "name":"Macbook Pro",
      "price":2500
   },
   {
      "name":"iPhone",
      "price":1200
   }
]

Console Routes

In this section, we will create a simple console route that we will call from the terminal

Open /routes/console.php

Add the following code

Artisan::command('monty', function () {
    $this->info('Spam eggs sausage spam sausage eggs');
})->describe('Display an important message from monty python');

HERE,

  • Artisan::command('monty', function () {...} defines a new command monty that we can access via artisan

Run the following command in the terminal

php artisan monty

Executing the above code produces the following results

Spam eggs sausage spam sausage eggs

We will talk more about creating artisan commands in future lessons.

Channel routes

Channel routes are used to broadcast messages to channels. Since this is an introductory lesson, we will skip channel routes for now and cover them in future lessons.

Named Routes

Routes are defined in a single place but used everywhere. The home page can have a link to products page. The about us page can also have the same link and so many places through out our application. Laravel allows us to name our routes so that we can use the route name instead of the actual URL.

Named routes are defined like so

Route::get('/', function () {
    return view('welcome');
})->name('home');

Route::get('/about-us',function(){
    return 'About us page';
})->name('about.us');;

Route::get('/pages/{name}',function($name){
    return "$name page";
})->name('pages');

HERE,

  • ->name('home'); the name method is used to name a route. In our above example, we have named our routes home, about.us and pages respectively.

Run the following command in the terminal

php artisan route:list --method=GET

You should be able to see the following routes listed

Laravel artisan routes

We will learn how to use named routes on the section on Laravel blade

Route Parameters

Laravel allows us to define routes that accept parameters that are passed as arguments to functions that respond to route requests. For example. we can have a products page and a user can pass in macbook as a parameter argument to get the details about a product with URL macbook.

Parameters are defined using curly brackets like so

Route::get('/products/{url}',function($url){
    return "$url page details";
})->name('products');

HERE,

  • Route::get('/products/{url}',function($url){...} defines a route products that accepts a parameter called url. We used curly brackets {url} to specify our parameter. Laravel allows you to use more than one parameter in route.

Load the following URL in your browser

http://localhost:8000/products/macbook

You will get the following results

macbook page details

Optional Parameters

Optional parameters are parameters that can be skipped when calling the route. For example, we can define a single route to handle both all categories listing and a single category. If the category URL is not passed in as an argument then we list everything else we list details for a single product.

Route::get('/categories/{url?}',function($url = null){
    return $url == null ? 'list all categories' : "display $url category";
})->name('categories');

HERE,

  • Route::get('/categories/{url?}',function($url = null){ defines an optional parameter url using the question mark ? at the end of the parameter. function($url = null) initializes our parameter url to null if no value is submitted.
  • return $url == null ? 'list all categories' : "display $url category"; returns list all categories if not argument is passed else the category details are displayed based on the passed in value.

Load the following URL in your browser

http://localhost:8000/categories
http://localhost:8000/categories/apple

You should be able o get the following results respectively

list all categories
display apple category

Route Middleware

Middleware allows us to perform some action before or after executing the route. For example, if a user needs to access a protected page then you can use the auth middleware to check if the user is logged in. If yes then you allow access else the user is redirected to a login page.

In this lesson, we will create two very basic middleware classes. One will execute before the route and the other will execute after the route.

Run the following artisan commands

php artisan make:middleware BeforeMiddleware
php artisan make:middleware AfterMiddleware

HERE,

  • The above commands create two classes BeforeMiddleware, and AfterMiddleware in the directory /app/Http/Middleware

Modify the code for BeforeMiddleware.php as follows

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
    public function handle($request, Closure $next)
    {
        echo "middleware before executing the route</br></br>";

        return $next($request);
    }
}

HERE,

  • echo "middleware before executing the route</br></br>"; prints a simple message in the browser. Under normal circumstances, you can perform some business logic here such as checking if a user has sufficient access rights to gain access to the page.

Modify the code for AfterMiddleware.php as follows

<?php

namespace App\Http\Middleware;

use Closure;

class AfterMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        echo "middleware after executing the route</br></br>";

        return $response;
    }
}

HERE,

  • $response = $next($request); the route is executed and the results assigned to the variable $response
  • echo "middleware after executing the route</br></br>"; prints a simple message in the browser to keep it simple. In normal cases, you can use the after middleware to work on the results that are returned after executing the middleware. For example, you can create middleware that takes the result i.e. data array and output the results as XML.

After creating the middleware, we need to register it in the Kernel. Open /app/Http/Kernel.php

Add the following lines to the $routeMiddleware array variable

'before' => \App\Http\Middleware\BeforeMiddleware::class,
'after' => \App\Http\Middleware\AfterMiddleware::class,

HERE,

  • 'before' => \App\Http\Middleware\BeforeMiddleware::class, defines a route middleware which can be accessed by passing in before as the argument to the middleware function on the Route class
  • 'after' => \App\Http\Middleware\AfterMiddleware::class, defines a route middleware which can be accessed by passing in after as the argument to the middleware function on the Route class

Let's now modify our web routes and add two more routes like so

Route::get('/admin',function(){
    return 'admin dashboard';
})->middleware('before');

Route::get('/analytics',function(){
    return 'analytics dashboard';
})->middleware('after');

HERE,

  • Route::get('/admin',function(){...} defines a route admin that calls the before middleware ->middleware('before')
  • Route::get('/analytics',function(){...} defines a route analytics that calls the after middleware ->middleware('after')

Load the following URLs in your browser

http://localhost:8000/admin
http://localhost:8000/analytics

You should be able to see the following results

middleware before executing the route

admin dashboard

middleware after executing the route

admin dashboard

You can also apply multiple middleware on a route like so

Route::get('/statistics',function(){
    return 'statistics dashboard';
})->middleware('before','after');

HERE,

  • ->middleware('before','after') applies the before and after middleware to the route statistics

Load the following URL in your browser

http://localhost:8000/statistics

You should be able to see the following results

middleware before executing the route

middleware after executing the route

statistics dashboard

Redirecting

Redirecting is loading a different URL from with a route during execution time. For example, if you have a URL that stores a resource in the database, you will want to redirect to the view item page after creating the resource.

The following code shows you how to redirect in Laravel

Route::get('/store', function () {
    return redirect('admin');
});

HERE,

  • return redirect('admin'); uses the built-in helper redirect to load the route admin

Load the following URL

http://localhost:8000/store

The web browser will redirect you to the following URL

http://localhost:8000/admin

Conclusion

Laravel offers a lot more functionality on routes such as grouping, namespaces and many more. We will cover some of the ore advanced staff as we progress with our tutorial series.

Summary

Laravel comes with a number of built-in functions that make it easy to define routes and work with them. Laravel supports web,api,console and channel routes. Middleware is used to inject business logic into routes which can be executed before or after executing the route. We can pass parameters to routes and can redirect from one URL to another.

What next?

In the next tutorial, we will introduce you to variables and learn what role they play in python applications. If you enjoyed this lesson then show us your appreciation by creating a free accounts.


...