Super Quick Tutorial: Laravel Domain Routing with new Routing File

Another Super Quick Tutorial, this time looking at domain routing for your application. Maybe you’ve got some specific admin functionality or client functionality or something you want to route, without clogging up your route files (which is an occupational hazard of working with Laravel).

The Problem / Situation

You want a separate route file for some specific routes, probably controlled by some specific functionality, and you want it to come from a separate file (rather than routes/web.php or routes/api.php)

The Super Quick Solution

Go to your app/Providers/RouteServiceProvider and add your own inclusion, it’ll probably look something like this;

// Give some middleware to all the routes in here
Route::middleware(['web', 'auth', 'admin'])

    // Remove this if you want, all these routes will be /admin/[your declaration]
    ->prefix('admin') 

    // All routes in here will be named admin.[your declaration]
    ->name('admin.')

    // Change as appropriate, these routes will look in this namespace for their controllers
    ->namespace("App\\Http\\Controllers\\Admin")

    // This is where you set what domain we're looking for here
    ->domain('admin.yourapp.com') 

    // Finally, include the file you want to add
    ->group(base_path('routes/admin.php'));

Also Consider

  1. How will this work when you deploy between environments?
  2. How are you going to declare the domain, perhaps as a configuration in your environment file
  3. Ensure you’re routing requests through your web server to this location, e.g. if you’re using Apache you might want to add a ServerAlias declaration to route these requests
  4. Finally, the other thing you might need to check are Session and Cookie settings, to ensure that anything that needs to be shared between application domains, can be

I'd love to hear your opinion on what I've written. Anecdotes are always welcome.

This site uses Akismet to reduce spam. Learn how your comment data is processed.