Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

brzoz's avatar
Level 2

Laravel simple API, just get controller response

Hi! I have a simple app:

  • laravel
  • puhppeteer (service),
  • controllers (getting data from puhppeteer service),
  • php+js views /no vue/ (getting responses from controller via ajax).

I want to get only two responses from controller usign ajax call. There is no users etc. How could I secure the api endpoints with passport or any other lib?

Every tutorial I've found requires users with some key assigned to them. I just need to make two ajax request from frontpage to two API endpoints. User won't login in. I want a user to visit the frontpage, put the url into the form input and get response from the controller.

How should I do that?

0 likes
2 replies
rodrigo.pedra's avatar

If you are using passport already read about client grants:

https://laravel.com/docs/8.x/passport#client-credentials-grant-tokens

If not, for restricting domains that can make requests to your endpoints, check your CORS configurations:

https://laravel.com/docs/8.x/routing#cors

Another option is adding a very simple auth guard that handles a token not attached to any user using this:

https://laravel.com/docs/8.x/authentication#closure-request-guards

===

If using this last option, the basic steps are this:

1 - Add this code to your AuthServiceProvider's boot method:

Auth::viaRequest('custom-token', function ($request) {
    return $request->input('token') === 'my-secret-token';
});

2 - Add this new guard to your app's ./config/auth.php file under the guards key:

'guards' => [
    'api' => [
        'driver' => 'custom-token',
    ],
],

3 - On your ./routes/web.php tell the routes to use that guard:

Route::get('/data', [MyController::class, 'index'])->middleware('auth:api');
Route::post('/data', [MyController::class, 'store'])->middleware('auth:api');

4 - Send that token with your ajax payload

Note that instead of sending the token as a input field you can send it as a header when using ajax calls.

Hope it helps

brzoz's avatar
Level 2

Thanks! 3rd options seems fine, but anybody can see the token code or console xhr. I'll try with CORS. ;)

Please or to participate in this conversation.