Laravel 10 continues to empower developers with its elegant syntax and robust features. One fundamental aspect of building dynamic web applications in Laravel is customizing routes. However, there are in-built route files in Laravel. The in-built routes are specified as web, api, channel, and console. Based on the application, sometimes the web and api routes are not sufficient to manage the large number of routes for a big application. The single route file will have to take care of all the routes that will be difficult to manage. However, Laravel provides the flexibility to create and manage the custom route file. This is a great way to manage routes easily in Laravel. In this beginner-friendly guide, we’ll walk through the process of creating a custom route file in Laravel 10. It allows you to tailor your application’s navigation with ease.
Understanding Laravel 10 Routing Basics
Routing is a crucial component of any web application. It determines how HTTP requests are handled. Laravel simplifies this process with a clean and expressive routing system. By default, routes are declared in the routes/web.php
file. It defines how the application responds to various URIs.
Therefore, let’s take a quick look at a basic route definition.
// routes/web.php
Route::get('/', function () {
return view('welcome');
});
In this above example, a route is defined for the root URI (/
), and it returns the welcome view when accessed.
If we already have the in-built routes, then the question is why do we need to create a Custom route in Laravel?
Well, let’s know this in the today’s post.
Recommended: Build a Contact Form in Laravel 10 to Send Emails Using Gmail with Attachment
Why Create a Custom Route?
A Custom route provides the flexibility to define specific URIs and associate them with the desired actions in your application. This customization is essential for creating user-friendly URLs and ensuring a seamless user experience.
Step 1: Creating a New Route File in Laravel
To keep our routes organized, let’s create a new file specifically for our custom route endpoints. Default, the routes folder architecture will look like this.
routes
|
|______ api.php
|
|______ channels.php
|
|______ console.php
|
|______ web.php
Now, in the routes
directory, create a file named custom.php
. Therefore, after creating this route file the directory structure will become like this.
routes
|
|______ api.php
|
|______ channels.php
|
|______ console.php
|
|______ custom.php // custom route file
|
|______ web.php
In the next step, you will have to define some route endpoints inside the custom route file.
Recommended: Handling Multiple File Uploads in Laravel with Livewire
Step 2 – Defining Custom Route Endpoint in Laravel
To define any route endpoint inside this custom route file, you will have to add a namespace at the top. Therefore, add the below namespace in the custom route file.
use Illuminate\Support\Facades\Route;
This is done. Now, you can add any custom route endpoints that you want to keep inside the custom route file.
As of now, I will add one endpoint with a closure function just for demonstration purposes as shown below.
<?php
use Illuminate\Support\Facades\Route;
// Route will go here
Route::get('custom-route', function() {
dd('Route in Custom Route File');
});
So, you can refer to the below screenshot as well.
However, If you try to access this defined route in the browser, it will throw a 404 (not found) exception.
This means the route endpoints which are defined inside the custom route file are not recognizable by the application.
Now, to make this custom route work, you will have to register this custom route file in the service provider.
Recommended: Scaling Laravel Apps with Efficient Many-to-Many Relationships
Step 3 – Register Custom Route File in RouteServiceProvider
You will have to register the custom route file in order to access the custom route file endpoints. Hence, navigate to the app/Providers/RouteServiceProvider.php
file.
Now, inside the RouteServiceProvider we have a boot method as shown below.
/**
* Define your route model bindings, pattern filters, and other route configuration.
*/
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
You will see by default, api and web route files are registered with the middleware. Similarly, you will have to register the custom route file just after the web route.
Hence, after registering the custom route file, the boot method will look like as shown below.
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to your application's "home" route.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*/
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
// Register Custom Route
Route::middleware('web')
->group(base_path('routes/custom.php'));
});
}
}
That’s all for the functionality. Now, let’s switch to the browser window and try to access the custom route endpoints. So, for that, let’s navigate to the custom-route endpoint in the browser.
http://localhost:8000/custom-route
And here we go. The custom route is accessible now in the browser.
So, that’s all for this post. Finally, we have created the custom route file and used the endpoints.
Conclusion
Congratulations! You’ve successfully created and integrated custom routes into your Laravel 10 application. This foundational knowledge empowers you to build more dynamic and user-friendly web applications. As you continue your Laravel journey, explore additional features, such as route parameters, middleware, and resourceful routes. However, this guide serves as a starting point, and with practice, you’ll gain confidence in leveraging Laravel’s powerful routing capabilities. Happy coding!
Leave a Reply