Search code examples
phplaravelurllaravel-10

Laravel - How to release only API routes


I developed a web application with React frontend and Laravel for stateless API.

I would like to access to the frontend with the url "http://localhost/my-application" and the backend's API with the url "http://localhost/api/my-application/".

I created the folder "www/api/my-application" and here I put a symlink of public index.php of my Laravel backend.

The problem is that to call the APIs, I have to put this url "http://localhost/api/my-application/api/login".

As you can see I have to repeat "/api" because Laravel APIs have that default url. Also, if I try to just access to just "http://localhost/api/my-application/" I get a page with 500 Server Error, and the log says

ERROR: View [welcome] not found. {"exception":"[object] (InvalidArgumentException(code: 0): View [welcome] not found.

This is because it tries to access to the view. But I don't have any views, I would like that my Laravel project has just API stuff

How to clean the project so that I just have to access to "http://localhost/api/my-application/" to access to the APIs? So the "login" API, should be here: "http://localhost/api/my-application/login" and not here "http://localhost/api/my-application/api/login"


Solution

  • You can change the prefix for routes in RouteServiceProvider.php

    From this

    $this->routes(function () {
         Route::middleware('api')
            ->prefix('api')
            ->group(base_path('routes/api.php'));
    
         Route::middleware('web')
            ->group(base_path('routes/web.php'));
    });
    

    To this

    $this->routes(function () {
         Route::middleware('api')        
            ->group(base_path('routes/api.php'));
    
         Route::middleware('web')
            ->prefix('web')
            ->group(base_path('routes/web.php'));
    });
    

    In this way you are removing the prefix for API routes and adding a prefix web/ to web routes.

    Then from your frontend just hit the endpoint http://localhost/api/my-application/login

    Also, you could give a try by removing the web Route middleware from provider to disable it.