javascriptphplaravelvue.jsinertiajs

Consume API endpoint from Laravel + Inertia App


I have an App created with Laravel with InertiaJS and VueJS. It is set with all the Jetstream scaffolding for the Authentication, everything from the auth is handled by jetstream and inertia.

The problem is that I have a couple of pages that need to call the api.php routes in my project, for example in my Vue.JS page:

fetch(`/api/v1/companies/${this.user.id}`)
    .then(response => response.json())
    .then(res => {
           console.log(res)
});

And this is a simple endpoint in my api.php:

Route::get('/companies/{user_id}', [Controller::class, 'index']);

How can I make this endpoint auth protected, so only authenticated users get access (like with Laravel Sanctum), but in the Inertia environment? Is there a way to put this endpoint behind a middleware and send a token from the Vue.JS page?


Solution

  • So, just in case anyone ends up here with the same problem, I ended up solving this by generating a token by myself in the backend and sending it to the view. I don't think this rises a security problem, but I am no expert.

    So what I did was, in the controller:

    $user = Auth::user();
    $token = $user->createToken('a secret variable')->plainTextToken;
    

    And send it to the view (or append it to the user). Then, just use it in the view to call an endpoint protected with:

    Route::middleware('auth:sanctum')->get('/companies/{user_id}', [Controller::class, 'index']);
    

    And making a fetch in the view, with the token like @Omar Corrales sugested.

    But I think the web route with the first controller must be under the same middleware form auth:sanctum. I hope this helps someone in the future.