Laravel Routing Tutorial Complete Guide [Updated]

Laravel Routing Tutorial Complete Guide

Laravel Routing Tutorial
Laravel Routing Tutorial

 

The fundamental function of any web application framework is to get HTTP requests from a user and deliver HTTP responses.

The Laravel Routing mechanism maps the user HTTP requests to respective controllers and closures. Routes are also known as application URLs. Defining, an application route is the first task of creating web application/website.

This post will provide everything you need to understand about Laravel Routing mechanism.

Learn Laravel Tutorials:

If you are a beginner to Laravel Framework, then we recommend you to read the following topics:

What is Route in Laravel?

A Laravel route is a web request URL that accesses a particular web page of your application.

Laravel Routing is a process of accepting the user requests and redirecting to associated controller functions. In simple terms, you can see the route as an entry point of specific page URL from where the request is passed to appropriate route handlers (controller functions).

So, defining a route is the first task of Laravel web development.

Understanding Laravel Route Files

From Laravel 5.5 onwards, web routes are defined under “routes/web.php” and API routes in “routes/api.php”. The web routes are defined for end-users, API routes for your API, we will focus more on routes/web.php.

Prior to Laravel 5.3, all the routes were defined in app/Http/routes.php single file.

Laravel Routing Types

Laravel supports the following main types of routing:

  • Basic Routing

  • Parameterized Routing

  • Named Routing

 

Laravel Development Company in Delhi India
Laravel Development Company in Delhi India

Laravel Basic Routing

This is the simplest way to define a route where a route is mapped to a specific path (i.e URL) with a Closure.


// routes/web.php
   Route::get('/', function () {
   return 'Hello, World!';
   });
  

What is Laravel Closure?

A closure in Laravel is an anonymous function definition that you can pass around as an object, assign to a variable, pass as a parameter to other functions and methods, or even serialize.

Here, we have defined a basic route, if anyone visits / (the root of your domain), Laravel’s router should run the closure defined there and return the result. Note that we return our content and don’t echo or print it.

 

More route examples:

Observe the following example to understand more about Routing

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

You can also read Laravel Routing guide from Laravel official documentation here.

Must read guides on OpenCart and JavaScript:

Powerful Features of JavaScript That Every Developer Should Know!!

How PHP Connect to MySQL Tutorial with Example

How to install OpenCart on LAMP/WAMP Server?

What is OpenCart? Features of OpenCart!

Ultimate PHP Composer Package Manager Tutorial

                                           Subscribe to Newsletter


Laravel Route Methods:

The router allows you to register routes that respond to any HTTP verb:

  • get           –  Route::get($uri, $callback);
  • post        –  Route::post($uri, $callback);
  • put          –  Route::put($uri, $callback);
  • patch      –  Route::patch($uri, $callback);
  • delete     –  Route::delete($uri, $callback);
  • options  –  Route::options($uri, $callback);

Can we register a single route for multiple HTTP requests?

Yes. Laravel provides flexibility to register a single route function to be called in response to multiple HTTP requests. This can be achieved using the “match” method like below:

Route::match(['get', 'post'], '/userList', function () {
    //
});

Responds to both userList GET and userList POST methods.

 

Register route to respond to all the HTTP request types:

A single route can be registered to respond to all HTTP requests.

Route::any('foo', function () { 
    //
});

 

Laravel Route Handling:

As we have seen the simple way to handle route is using the Closure in the route file itself. But, in large web applications, all the routing logic is segregated to separate file called as Controllers.

Secondly, applications using closures can’t take advantage of Laravel’s Routing Cache.

Routes calling Controller methods:
Route::get(‘/’, ‘WelcomeController@index’);

This method direct Laravel framework to pass all HTTP requests to index() method of the App
\Http\Controllers\WelcomeController controller. This method will be passed the same parameters and treated the same way as a closure you might’ve alternatively put in its place.

 

#Parameterized Routing

Route parameters are always encased within {} braces and should consist of alphabetic characters, and may not contain a – character. Instead of using the – character, use an underscore (_).

Route parameters are injected into route callbacks/controllers based on their order – the names of the callback/controller arguments do not matter.

1. Required Parameters

If the routes are invoked with some data, i.e parameters – that can be passed to closures or controller methods.

Route::get('users/{id}/friends', function ($id) {
//
});

 2. Routes with Optional Parameters:

In this case, you should also provide a default value for the route’s corresponding variable. You may do so by placing a? mark after the parameter name. Make sure to give the route’s corresponding variable a default value:

Route::get('user/{name?}', function ($name = null) {
return $name;
});

Route::get('user/{name?}', function ($name = 'John') {
return $name;
});

# Named Routing – Name the Complex Routes

Route names are referenced with the exact path in any part of the application. The most common place is Views where we have to refer to routes too. There’s a URL() helper to simplify that linking in your views. The helper will prefix your route with the full domain of your site.

<a href="<?php echo url('/'); ?>">
// outputs <a href="http://myapp.com/">

Laravel gives us the flexibility to define simple route names to complex and long URL’s, using which we need not refer to these complete URL’s. Means we can give nicknames to urls.

// Defining a route with name in routes/web.php:
Route::get('members/{id}', 'MembersController@show')->name('members.show');

// Link the route in a view using the route() helper
<a href="<?php echo route('members.show', ['id' => 14]); ?>">

The name() method allows naming the route. route() method is used when using named routes which link the specified route name to named routes.

 

Laravel Routing/Route Group

Laravel routes can be grouped together to share specific characteristics like – a certain authentication requirement, a path prefix, or perhaps a controller namespace. Defining these shared characteristics again and again on each route become a very tedious task for developers.

Laravel Route groups allow developers to group several routes together, and apply any shared configuration settings once to the entire group, to reduce code duplication.

To achieve this, shared attributes are specified in an array format as a first parameter to the Route:group() method.

How to create a Laravel route group? The following code snippet gives an example:

Defining a route group:

Route::group([], function () {
Route::get('hello', function () {
return 'Hello';
});
Route::get('world', function () {
return 'World';
});
});

Note that the empty array in route group does not make any difference, however, allows you to pass a variety of configuration settings that will apply to the entire route group. The configurations are passed using the middlewares.

Laravel Route Middleware:

Essentially, Laravel route groups are defined using middlewares to apply the specific configuration on a group of routes.

The middleware method is used to assign middleware to a group of routes. If multiple middlewares are defined, they are executed in the order they are defined. Laravel uses for authenticating users and restricting guest users from using certain parts of a site.

Example – Restricting a group of routes to logged-in users only:

Route::group(['middleware' => 'auth'], function () {
   Route::get('admin_dashboard', function () {
        return view('admin_dashboard');
   });
    Route::get('admin_account', function () {
        return view('admin_account');
    });
});

Here, we’re creating a route group around the admin_dashboard and admin_account views and applying the auth middleware to both. it means users have to be logged in to the application to view the dashboard or the account page.

Applying Middleware in Controllers

Rather than attaching a middleware to route definition, Laravel allows us to also attach middlewares to route controller classes. This can be done by calling the middleware() method in the constructor function of the Controller class. The parameters passed to the middleware() method is the name of the middleware, and you can optionally chain modifier methods (only() and except()) to define which methods will receive that middleware:

class AdminDashboardController extends Controller
{
   public function __construct()
   {
      $this->middleware('auth');
      $this->middleware('admin-auth')
      ->only('admin');
      $this->middleware('team-member')
      ->except('admin');
   }
}

Laravel Routing Prefix – Prefix Path to Laravel routes

If the laravel application has a group of routes that commonly share a path, then those routes can be prefixed with a given URI. The Laravel prefix() method can be used to prefix route groups with a specific prefix.

For example, if you want to prefix all of the grouped route’s names with “admin.”:

Route::prefix('security')->group(function () {
        Route::get('users', function () {
        // Matches The "/security/users" URL
        });
    });

Laravel Subdomain Routing:

One of the most powerful built-in features of Laravel is its support for subdomain routing. Using Laravel subdomain routing, You can define a route “{subdomain}.myapp.com” and the value of the subdomain is passed to the route handler as a parameter.

This helps developers to do some other logic to present the correct content to the user based on the subdomain.

Route::group(['domain' => '{account}.myapp.com'], function () {
Route::get('/', function ($account) {
//
});
Route::get('users/{id}', function ($account, $id) {
//
});
});

Redirect Route in Laravel

Normally, We have returned views from a controller method or route definition. There can be a route that needs to return another URI. The Laravel Route::redirect() method is used to redirect a route to another route.

Route::redirect('/route1', '/route2');

By default, Route::redirect returns a 302 status code. You may customize the status code using the optional third parameter:


 Route::redirect('/route1', '/route2', 301);

You may use the Route::permanentRedirect method to return a 301 status code:

 Route::permanentRedirect('/route1', '/route2');

View Routes:

When you want to return the only view from the route, then Route::view() method can be used to do the same. This shortcut method so that we don’t have to define complete route path and make view returns.

Route::view('/homePage', 'homePage');

Route::view('/homePage', 'homePage', ['name' => 'TechCluesBlog']);

Here, the view() method accepts a URI as its first argument and a view name as its second argument.

Laravel Fallback Route – The awesome feature!!

What will happen if none of the defined routes matches with the HTTP request URI, Laravel will handle it automatically
and render “404” using exception handler to the user. From Laravel 5.5 onwards, we can define the fallback mechanism to cater to these scenarios and register fallback routes to handle unhandled requests to avoid application unexpected results.

Route::fallback(function () {
//
});

NOTE – The fallback route should always be the last route registered by your application.

Laravel API Rate Limit – Rate Limiting [Limit the number of requests to specific route]

Imagine a serious developer, if you want to limit or restrict the number of requests per unit time in Laravel.

Yes. Laravel provides those great functionality called Rate Limiting, i.e limiting the number of requests using a middleware. rate limiting helps developers to develop secure web applications, prevent DOS attacks, this making application available for legitimate users.

The ‘throttle’ middleware is used to single route or group of routes.

Route::middleware('auth:api', 'throttle:60,1')->group(function () {
    Route::get('/getUserList', function () {
    //
    });
});

 

Conclusion:
In this post of Laravel Routing Tutorial, you have learned about basic concepts of Laravel routing, types of routing, Named routes. Also, refer to Laravel routing groups…

Subscribe to our Blog @ TechCluesBlog

 

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *