All You Need To Know Laravel Routing

In this article, we will discuss Laravel Routing in depth. Laravel provides the wonderful feature to make routing easy and simple. We can manage each of the URLs from a single file.

Today we will not only explore the types of the route and its features. We will discuss more closely Laravel Routing. These scenarios include Basic Routing, Route Parameters, Named Routes, Route Groups, Route Modal Binding, Rate Limiting and many more.

Route Files

All Laravel Routes are defined in route files, which are located at “routes” directory. These files are automatically loaded by the framework. In the “route” directory, we are focusing on “web.php” and “api.php”.

  1. The “routes/web.php” file contains all the routes that are for the web interface. Web middleware group is assigned to these routes and provides the features like session / CSRF Protection.
  2. The “routes/api.php” file contains all the routes that are for Mobile App interface or applications which required stateless API. API middleware group is assigned to these routes.

Available Route Methods

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

Laravel also provide support for multiple HTTP requests in single route declaration. You may do this using “match” method. For example:

Route::match([methods], $uri, $callback);

Route::match(['get','post'],'/profile','UserController@profile');

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

#CSRF Protection

You should need to add the CSRF token in your forms which required POST, PUT or DELETE routes. You can get more details on CSRF Protection here.

# Setup Testing Application

I’m assuming you are familiar with the Laravel framework. So we are not discussing the scratch setup of Laravel framework. If you are not familiar with Laravel then please follow the given links.

I’m going to use “laratest” as the Laravel application name. You can create as per your need.

# Basic Page Routing

Let’s open the routes/web.php where we create all of the application routes. Here we are adding routes to our pages such as home, about and contact.

// Home Page
Route::get('/', function(){
  return view('/home');
});

// About Page
Route::get('/about', function(){
  return view('/about');
});

// Contact Page
Route::get('/contact', function(){
  return view('/contact');
});

These route uses get method, and return the required view. All the views are located in resources/views directory.

Now you can visit yourdomain.com, yourdomain.com/about, and yourdomain.com/contact or if you are working in the local environment you can use app virtual host, for example, laratest.local for the home page, laratest.local/about and laratest.local/contact for inner pages.

# Static view routing

If you want to return a static view with your route. You can use Route::view method. In the view method, the first argument is a URI and second argument is a view name.

Route::view('/', 'home'); // Home page
Route::view('/about', 'about'); // About Page
Route::view('/contact', 'contact'); // Contact Page

In addition, when you want to sent data to view then you may provide an array of data to pass to the view as an optional third argument. For example:

Route::view('/protfolio', 'portfolio', ['sort' => 'DESC']);

# Page Routing with parameters

Whenever we need to send the id or anything else as a parameter for the route. For example:

Route::get('user/{id}', function ($id) {
  return 'User '.$id;
});

You may define as many parameters as per your requirement.

Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
  //
});

All the route parameter are mentioned within {} braces and contains alphabetic characters. In route parameters – hyphen character is not allowed but you can use an underscore (_).

Optional Parameters

Laravel also an option to create route with optional parameter. You may add ? question mark after the parameter name to made parameter optional. For example:

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

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

# Handling Redirection using the route

If you want to redirect the route to another URI. You can use Route::redirect method. It’s a simple shortcut and no need to define the full route or controller for the simple redirect.

Route::redirect('/uri-1', '/uri-2', 301);

# Filter routing with regular expressions

You can apply the specific format to the route parameters using the where method. The where method accepts the name of the parameter and a regular expression. For example:

Route::get('user/{name}', function ($name) {
  //
})->where('name', '[A-Za-z]+'); // only alphabets accepted for name parameter

Route::get('user/{id}', function ($id) {
  //
})->where('id', '[0-9]+'); // only digits accepted for id parameter

Route::get('user/{id}/{name}', function ($id, $name) {
  //
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']); // multiple parameter with required expressions

# Named Routing

Named Route to provide an easy way to remember the routes using the specific names. For example:

Route::get('/user/list', 'UserController@listUser')->name('listUser');

After assigning the name to the route, you can use route name where you want to redirect.

return redirect()->route('listUser');

When we need to send parameters with the named route. Then add the second argument to the routing method. For example:

Route::get('user/{id}/details', function ($id) {
  //
})->name('userInfo');

$url = route('userInfo', ['id' => 1]);

# Admin Section Routing with group route, prefix, middleware

Route groups allow you to add multiple route attributes, such as middleware, namespaces, prefix or etc to a large number of routes without defining those attributes on each individual route. You can use Route::group method and add attributes in an array format. For example:

Route::group(
  [
    'prefix' => 'admin',
      'middleware => [
      'auth',
      'roleAdmin'
    ]'
  ], function() {

  Route::get('/dashboard', 'AdminController@dashboard');
  // Route which need admin prefix

});

 

# Conclusion

In this article, I’m trying to explain how to work with Laravel Route. Routing is a best Laravel feature, It allows us to manage all of the application routes from a single file. Also, It’s easy to maintain the application.

# What’s Next?

We will discuss more on Laravel Routing, Lot’s more things still not discussed in this article. I’m trying hard to make more tutorials on Laravel. We will continue in next article with Routing Groups with middleware, namespace, prefix, subdomain routing and many more in this series. Feel free to comment if any query.

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

LaravelLaravel RoutingRedirect RouteRegular ExpressionsRoutingRouting GroupsRouting MethodView Route
Comments (3)
Add Comment
  • deepak

    Thanks for it here I got all possible way of routing

  • joaquin

    Laravel has the most verbose routing system I’ve seen in several PHP frameworks.
    Is there a way to just have a general routing pattern to “controller/action/id” as in most MVC frameworks?.
    Writing a route for every action, for every view and for every AJAX callback is not practical, error prone (more code) and lower performance.

    • Pankaj Sood

      Hi Joaquin, check this link. Hope this will helps you.