LARAVEL

Fluent Routing in Laravel 5.2


This is a series of posts that showcase new features and aha moments in Laravel 5.2

1. Implicit Route Model Binding

2. Simplified Eloquent Global Scopes

3. Append Scheduled Tasks Output

4. Form Array Validation

5. Middleware Groups

6. Auth Scaffolding

7.  Api Rate Limiting

8. More helper functions

9. Fluent Routing

Introduction

Laravel 5.2 has come bundled with a lot more options of doing things and one of those beautiful options is Fluent routing.

Now, this Fluent Routing option has been available since Laravel 5.1.17.

I am only reiterating it now in Laravel 5.2 because a lot of developers are really not aware of it yet.

Fluent routing is the ability to chain several methods used in routing to give a very nice and fluent interface.

Example

In Laravel 5.1 < Laravel 5.1.17,  we can write a route like so:

Here this route uses the SongController, invokes the api middleware, has a prefix of /api/v2 and has a named route of singleSong.

We had to pass all those options into an array.

In Laravel 5.1.17 <= Laravel 5.2, we can simply just chain them as methods anyhow we like it like so:

From the code above, we have the following methods:

1. prefix  => for appending prefixes to your routes

2. middleware => for applying middleware, here you can also pass in an array of several middlewares.

3. name => for named routes

Try it out and see the awesome fluent blessing for yourself.

Let me show you the code that makes this possible.

Go into your vendor/laravel/framework/src/Illuminate/Routing/Route.php

From line 623 to 636:

prefix

From 761 to 772:

name

From line 229 to 250:

middleware

return $this in each of those methods is what gives it the ability to be chained to other methods.

Conclusion

There are lots of hidden treasures in large sets of codebase. Take time to explore Laravel Codebase, every day you’ll learn something new and become better at writing and organizing good code.

Note: The version of Laravel used here is 5.2.0

Please, let me know if you have any questions or observations in the comments section below :smile:

 

PROSPER OTEMUYIWA

About PROSPER OTEMUYIWA

Food Ninja, Code Slinger, Technical Trainer, Accidental Writer, Open Source Advocate and Developer Evangelist.