Stoyan Georgiev
Stoyan Georgiev

Reputation: 305

How to route my API endpoints in Laravel as api.domain.com instead of domain.com/api

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

Upvotes: 2

Views: 3296

Answers (1)

Stoyan Georgiev
Stoyan Georgiev

Reputation: 305

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

Upvotes: 1

Related Questions