Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel subdomain routing is not working

I'm trying to have an admin subdomain (like this)

Route::group(['domain' => 'admin.localhost'], function () {
    Route::get('/', function () {
        return view('welcome');
    });
});

but admin.localhost acts just like localhost. How I'm supposed to do this correctly?

I'm using Laravel 5.1 and MAMP on OSX

like image 624
01000110 Avatar asked Jan 17 '17 17:01

01000110


2 Answers

Laravel's example...

Route::group(['domain' => '{account}.myapp.com'], function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});

Your code

Route::group(['domain' => 'admin.localhost'], function () {
    Route::get('/', function () {
        return view('welcome');
    });
});

If you look at the laravel example it gets the parameter $account in the route, this way we can route according to this variable. This can then be applied to the group or any route's in it..

That said, if it's not something driven by your database and you just want it with admin subdomain i would personally do this as a nginx config.

If you want to test nginx locally (easier) i personally recommended doing development with docker.

Hope this answers your question, if not let me know and ill try to answer for you.

like image 187
Matt The Ninja Avatar answered Sep 22 '22 14:09

Matt The Ninja


Laravel processes routes on a first-come-first-serve basis and therefore you need to place your least specific routes last in the routes file. This means that you need to place your route group above any other routes that have the same path.

For example, this will work as expected:

Route::group(['domain' => 'admin.localhost'], function () {
    Route::get('/', function () {
        return "This will respond to requests for 'admin.localhost/'";
    });
});

Route::get('/', function () {
    return "This will respond to all other '/' requests.";
});

But this example will not:

Route::get('/', function () {
    return "This will respond to all '/' requests before the route group gets processed.";
});

Route::group(['domain' => 'admin.localhost'], function () {
    Route::get('/', function () {
        return "This will never be called";
    });
});
like image 20
BrokenBinary Avatar answered Sep 22 '22 14:09

BrokenBinary