Skip to content

Commit ba1a43f

Browse files
committed
optimize auth requests
increases the performance of HTTP requests requiring sanctum authentication
1 parent f163cc8 commit ba1a43f

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

app/Models/PersonalAccessToken.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
namespace App\Models;
4+
5+
use Laravel\Sanctum\PersonalAccessToken as SanctumPersonalAccessToken;
6+
7+
class PersonalAccessToken extends SanctumPersonalAccessToken
8+
{
9+
/**
10+
* @param array $options
11+
* @return void
12+
*/
13+
public function save(array $options = []): void
14+
{
15+
$changes = $this->getDirty();
16+
17+
/**
18+
* Update the last_used_at field no more than 1 time per minute.
19+
* This change increases the performance of HTTP requests requiring sanctum authentication.
20+
*/
21+
if (
22+
!array_key_exists('last_used_at', $changes) ||
23+
count($changes) > 1 ||
24+
!$this->getOriginal('last_used_at') ||
25+
$this->getOriginal('last_used_at') < now()->parse($changes['last_used_at'])->subMinute()
26+
) {
27+
parent::save();
28+
}
29+
}
30+
}

app/Providers/AppServiceProvider.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace App\Providers;
44

55
use App\Helpers\Image;
6+
use App\Models\PersonalAccessToken;
67
use Illuminate\Auth\Events\Lockout;
78
use Illuminate\Auth\Notifications\ResetPassword;
89
use Illuminate\Auth\Notifications\VerifyEmail;
@@ -13,6 +14,7 @@
1314
use Illuminate\Support\ServiceProvider;
1415
use Illuminate\Support\Str;
1516
use Illuminate\Validation\ValidationException;
17+
use Laravel\Sanctum\Sanctum;
1618

1719
class AppServiceProvider extends ServiceProvider
1820
{
@@ -108,5 +110,9 @@ public function boot(): void
108110
trim(implode(' ', [$device->getClient('name'), $device->getClient('version')])),
109111
])) ?? 'Unknown';
110112
});
113+
114+
Sanctum::usePersonalAccessTokenModel(
115+
PersonalAccessToken::class
116+
);
111117
}
112118
}

0 commit comments

Comments
 (0)