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

Corbin's avatar

How do I customize the Laravel 8 Fortify/Sanctum JSON response on Login and Register with an API Resource?

I'm using Laravel 8 Sanctum and Fortify for a single page application. What I want to do is output custom JSON (A User API resource) when the user logs in and when they register.

Here's the JSON Resource:

UserResource.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'hashed_id' => $this->hashed_id
        ];    
    }
}

In the docs it looks like there's a way to do this in the boot method, potentially? But it doesn't specifically state how to customize the JSON output in the request:

{
				id: 1,
				name: 'corbin',
				hashed_id: '2kjh2kh432h48erhdfhifdhdfsfds'
}

What's the convention to do this? It's pretty routine and Im pretty surprised nothing popped out in the docs about it because most SPA's need to store info on login and register in local storage.

0 likes
5 replies
Corbin's avatar

@SilenceBringer so something like this?

use Laravel\Fortify\Contracts\LoginResponse;
use App\Http\Resources\UserResource;

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    $this->app->instance(LoginResponse::class, new class implements LoginResponse {
        public function toResponse($request)
        {
            return new UserResource($request);
        }
    });
}
TVercruysse's avatar

You need to register the (custom) App\Providers\FortifyServiceProvider in your config\app.php otherwise it will use the (default) package provided service provider.

Please or to participate in this conversation.