2

I am building a RESTful API for the first time using Laravel 5.8.

I want my routes/api.php to point to api.mysite.test

My question is very similar to Laravel 5.8 use subdomain as API endpoint beside domain.com/api

The accepted answer to the question above is

As for the API subdomain, I would just park it on top of the main domain. Then you don't have to worry about what directory it's pointed at.

I don't understand it very well, but I want to be able to use mysite.test as a web interface, presenting the API.

So far I removed the prefix from mapApiRoutes in RouteServiceProvider.php and tried to concatenate the subdomain

protected function mapApiRoutes()
    {

        Route::domain('api.'.url('/'))
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    } 

My routes/api.php:

<?php

use Illuminate\Http\Request;

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});


Route::apiResource('resources', 'ResourceController');

In /etc/hosts:

192.168.10.10   mysite.test

In .env:

APP_URL=mysite.test

In config/app.php

'url' => env('APP_URL'),

When I try to reach my resource

GET api.mysite.test/resources results in Could do not get any response

Also bothers me that

>>> url('/')
=> "http://localhost/mysite.test"

instead of mysite.test as I stated in .env

3
  • The change you did in the mapApiRoutes was what you should do. Try to add 192.168.10.10 api.mysite.test in your hosts file, as well Commented Oct 1, 2019 at 9:49
  • when I add 192.168.10.10 api.mysite.test to /etc/hosts for GET api.mysite.test/resources I get HTML response with status '404 not found' Commented Oct 1, 2019 at 10:46
  • If I hardcode Route::domain('api.mysite.test') in mapApiRoutes works fine, but why url('/') generates "http://localhost/mysite.test"? It's wierd? Commented Oct 1, 2019 at 10:59

1 Answer 1

1

I got myself sorted. So first as Mauro Baptista pointed in the comments all subdomains have to be added to /etc/hosts. In my case

192.168.10.10   mysite.test
192.168.10.10   api.mysite.test

It turns out there's no problem that they share the same IP address.

The second problem was my URL generation in RouteServiceProvider.php Route::domain('api.'.url('/')) does not produce valid URL. Instead the proper syntax is Route::domain('api.'.parse_url(config('app.url'), PHP_URL_HOST)) Credit to Adding a Subdomain to Your Laravel Application

Sign up to request clarification or add additional context in comments.

1 Comment

Route::domain(env('app_domain')) does also work if you add "app_domain" and assign api.mysite.test under .env

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.