inertiajs / inertia-laravel

The Laravel adapter for Inertia.js.
https://inertiajs.com
MIT License
2.08k stars 234 forks source link

Question - check if request comes from Intertiajs components or API #518

Closed qwasyx0 closed 1 year ago

qwasyx0 commented 1 year ago

am wondering if there is a way to check on the backend (Laravel) if the request (for example GET /posts) comes from an Inertia frontend or from other source (like Postman API).

For now it seems if I wanted to make a public API for shared routes (like CRUD of Posts model), I would have to make separate routes, because the controller returns a server-side rendered Vuejs component.

Is there a way to do something like this:

public function index()
{
    $this->authorize('viewAny', Post::class);

    if(request()->isInertiaRequest()) {      //<- check if the request is API or Vuejs Inertia frontend
        return inertia('Posts/Index', [
            'posts' => PostResource::collection($this->postService->index()),
        ]);
    }
    return PostResource::collection($this->postService->index());
}

I feel like writing separate API and Inertia routes would go against DRY, as the returned data would be the same resource.

rojtjo commented 1 year ago

I'm not sure if this is documented, but you can use the inertia helper on the request: request()->inertia() It basically just checks if the request contains the X-Inertia header.

See: https://github.com/inertiajs/inertia-laravel/blob/master/src/ServiceProvider.php#L75-L77

boring-dragon commented 1 year ago

@qwasyx0 you could tweak it like this just like @rojtjo mentioned

public function index()
{
    $this->authorize('viewAny', Post::class);

    if(! $request->inertia() && $request->expectsJson())  {  
         return PostResource::collection($this->postService->index());
    }

   return inertia('Posts/Index', [
            'posts' => PostResource::collection($this->postService->index()),
   ]);

}
jessarcher commented 1 year ago

Hi there,

Thanks for reporting the problem you are encountering, but it looks like this is a question that may be better suited for a support channel. We only use this issue tracker for reporting bugs with the library itself. If you have a question on how to use the functionality provided by this repository, you can try one of the following channels:

However, this issue will not be locked, and everyone is free to discuss solutions to your problem!