Laravel Routing Made Easy

Laravel Routing Made Easy

Routing is one of the core elements of any web framework. Laravel Routing is very easy and simple to use because of its flexibility.

In this post, we will look at how routing can be used to generate user and SEO friendly URLs. So let’s dive into this topic.

What is Laravel Routing?

Routing is a way of creating a request URL for your application. The best thing about the Laravel routing is you are free to define your routes the way you want it to look alike.

In Laravel, all requests are mapped with the help of routes, all routes are created inside routes folder. For you web application you can define application related routes in web.php file while for API all routes are defined in api.php file.

Here is how the route for web looks like.

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

Above code example will define a route which will recieve a / request and will return welcome view.

Defining routes in Laravel are super simple, you start a new route with Route:: facade and then followed by the request type you want to assign to that route. The function that executes in term of processing the request will come after. Here are all routes methods or request types you can use in Laravel.

  • get
  • post
  • put
  • delete
  • patch
  • options

Using Routing with Controller Functions

You can pass a controller method to a route. When the user will hit the route, the method of the defined controller will be triggered to perform the actions.

Instead of passing a closure function in the second parameter of a route, you can pass a controller with it’s method like below:

Route::get('/about', 'WebController@about');

In above code snippet, route start with Route:: facade and then the request method you are using like get.
Next, we define a route (/about) and then define the controller along with its method that you want to bind with this route by adding the @ symbol before the method name.

Using Parameters in Laravel Routing

Just like other web frameworks, it’s possible to pass a parameter in Laravel Routes. Let’s create a route which will take a number and then print it on the screen.

Route::get('/page/{number}', function ($number) {
	echo "Your are on page ". $number;
});

In the above code snippet, we created a route which will take a number parameter and passed it to the route function.

Now, whenever you visit /page by passing number parameter for instance /page/21, it will print on screen You are on page 21. The number parameter could be any number.

Using Optional Paraments with Default Values

It is also possible to make the route’s parameter/parameters optional. Just add a ? at the end of the parameter name and it will become an optional parameter. For example, for the above code example, we can change the parameter to be optional just like below.

Route::get('/page/{number?}', function ($number = 1) {
	echo "Your are on page ". $number;
});

Now if we visit the route without passing any parameter, by default $number will be set to 1. In the previous code example, if we don’t pass any value it will throw an exception as the parameter is not optional.

Using Regular Expressions in For Routing Parameters

In the above code example, our parameter $number will take any input like string, but what about if we want to restrict the parameter type to be a valid number. In Laravel, we can set the constraints on the route by adding a where method on route instance. Where the method will take the name and a regular expression rule for that parameter. Let’s define a constraint on our above route to only accept a valid number.

Route::get('/page/{number?}', function ($number = 1) {
	echo "Your are on page ". $number;
})->where('number', '[0-9]+');

In the above code example, we have defined a rule to accept only valid number for number parameter. Now if you try to pass a string, it will thorugh a NotFoundHttpException.

Naming Your Routes in Laravel

Laravel provides an easy way to name your routes by which we don’t have to hard code the URI’s in our blade views. For example, if we want to submit a form and want to add an action to a URL then we can just use the route name instead of passing a long URI.

You can define the route name by using the name method on the route instance like below.

Route::post('/submit', 'ContactFormController@submitForm')->name('contact.submit');

Now we can set the from action method like below:

<form action="{{ route('contact.submit') }}"></form>

Grouping Laravel Routes

Laravel Route Groups allow you to share route properties, such as prefix, middlewares, and namespaces across all routes within that group.

Shared attributes are specified in an array format as the first parameter to the Route::group method.

Route::group(['prefix' => 'posts', 'as' => 'posts.'], function () {
	Route::get('/', 'PostController@index')->name('index');
	Route::get('/create', 'PostController@create')->name('create');
	Route::post('/store' 'PostController@store')->name('store');
});

Above route group will create the following URLs:

  • /posts : with name posts.index
  • /posts/create : with name posts.create
  • /posts/store : with name posts.store

Above route group will prefix all routes within the group with posts and will attach the posts. name
to all routes’s names since we use the as => posts. in our route group.

It is also possible to create nested groups for routes. In our above code example, we want to make create and store routes to be only for authenticated users. For this, we will create another route group and add the two routes in that group by setting a middleware for the routes like below.

Route::group(['prefix' => 'posts', 'as' => 'posts.'], function () {

	Route::get('/', 'PostController@index')->name('index');

	Route::group(['middleware' => ['auth']], function () {
		Route::get('/create', 'PostController@create')->name('create');
		Route::post('/store' 'PostController@store')->name('store');
	});
});

Using Namespaces in Laravel Route Groups

We can also define the PHP namespace for the controllers using the route groups. Like below:

Route::group(['namespace' => 'Post'])
// this route group will load all controllers 
//from within the "App\Http\Controllers\Post"

Thus, in our above code example, we will define the namespace just like below.

Route::group(['namespace' => 'Post','prefix' => 'posts', 'as' => 'posts.'], function () {

	Route::get('/', 'PostController@index')->name('index');

	Route::group(['middleware' => ['auth']], function () {
		Route::get('/create', 'PostController@create')->name('create');
		Route::post('/store' 'PostController@store')->name('store');
	});
});

Note

Just for your information, you can also use the prefix(), namespace() and other route methods instead of using the array format as I used above. I prefer to use the array format as it make my code more cleaner.

Routing Cache

Laravel cache all routes to make your application fast. Sometime you might run into a situation when your routes will not work as expected. This might be due to the caching of your routes. You can use the below artisan command to clear all cached routes.

php artisan route:clear

If you want to cache the routes, you can run the below artisan command to cache all routes.

php artisan route:cache

Debugging Routes

You can find all the registered routes in your application using the below artisan command.

php artisan route:list

Using the above command, you can view the names, URLs, and middlewares used by the routes which is quite handy for debugging purpose.

Conclusion

Laravel provides very powerful routing system. To learn more about routing, you could also refer to the official Laravel Routing documentation.

Your little help will keep this site alive and help us to produce quality content for you.