Laravel: Normalize Social Links with AI Identity Resolver
A community directory can receive three different links for the same social profile before anyone notices the duplication. Tracking parameters, mobile URLs, and copied profile references make string cleanup look deceptively simple. Eventually, a collection of regular expressions becomes an unreliable identity system.
Identity Resolver provides a better boundary: submit a supported reference and receive a normalized public identity object. This tutorial builds a Laravel intake feature for Facebook, Instagram, and LinkedIn links, including persistence, bounded retries, deterministic tests, and operational safeguards.
Get access: this endpoint requires no token
- Open the official Identity Resolver documentation.
- Review the service and plan page.
- No account token or API key is required for the current public endpoint. There is no token to copy and no authorization header to configure.
- For optional registration or login, start from the service page and follow its account navigation. These links intentionally use the supplied official entry point; account creation is unnecessary for this integration.
The exact request is GET https://ai.mihajlo.mk/api/identity-resolver/v1/resolve. Supply platform and a supported username, id, identifier, profile, or url parameter. Our form accepts links, so it uses url.
curl --get \
--connect-timeout 2 \
--max-time 4 \
--header 'Accept: application/json' \
--data-urlencode 'platform=instagram' \
--data-urlencode 'url=https://www.instagram.com/instagram/' \
'https://ai.mihajlo.mk/api/identity-resolver/v1/resolve'
Build a small, synchronous intake feature
Use PHP 8.3+, Composer, PDO SQLite, and Laravel 12. The request passes through validation, a dedicated resolver client, and database persistence. Every submission remains pending moderation. Normalization establishes a public reference; it does not establish ownership, consent, or permission to publish.
Synchronous execution gives the submitter an immediate result. Two short upstream attempts are reasonable for this small form; a queue would add polling and lifecycle management without improving the initial experience.
composer create-project laravel/laravel community-directory "^12.0"
cd community-directory
touch database/database.sqlite
php artisan make:migration create_directory_submissions_table
Set these values in .env, replacing the database path with its absolute local path. No credential belongs here because this endpoint requires none.
DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/community-directory/database/database.sqlite
CACHE_STORE=database
SESSION_DRIVER=database
IDENTITY_RESOLVER_ENDPOINT=https://ai.mihajlo.mk/api/identity-resolver/v1/resolve
Add this entry inside the array returned by config/services.php. Application code reads configuration, allowing Laravel configuration caching to work correctly.
'identity_resolver' => [
'endpoint' => env(
'IDENTITY_RESOLVER_ENDPOINT',
'https://ai.mihajlo.mk/api/identity-resolver/v1/resolve'
),
],
The project adds three boundary classes under app/Services, one controller, one Blade form, and one feature test. It uses Laravel’s existing web middleware, database migrations, and HTTP client.
Preserve the normalized object without guessing its schema
The supplied contract describes a normalized public identity object without enumerating response fields. Preserve that complete object instead of inventing properties such as a canonical URL or permanent user ID. The application’s own platform, public_identity, and failure names below are local contracts.
Edit the generated migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::create('directory_submissions', function (Blueprint $table) {
$table->id();
$table->string('name', 120);
$table->string('platform', 20);
$table->json('normalized_identity');
$table->string('status', 20)->default('pending');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('directory_submissions');
}
};
Create app/Services/ResolvedIdentity.php and app/Services/ResolverFailure.php:
<?php
// app/Services/ResolvedIdentity.php
namespace App\Services;
final readonly class ResolvedIdentity
{
public function __construct(
public string $platform,
public \stdClass $publicIdentity,
) {}
}
<?php
// app/Services/ResolverFailure.php
namespace App\Services;
final class ResolverFailure extends \RuntimeException
{
public function __construct(
public readonly string $reason,
public readonly int $httpStatus,
) {
parent::__construct($reason);
}
}
Do not hash the complete JSON to deduplicate people. Object ordering, optional metadata, and changing profile details can defeat that approach. A uniqueness constraint requires a documented platform identifier and an explicit policy for changed handles.
Bound network work and classify failures
Create app/Services/IdentityResolver.php. It retries connection failures and HTTP 502, 503, or 504 once, with jitter. Validation failures, authentication failures, and rate limits receive no automatic retry. Redirects are disabled, and submitted URLs travel only as query parameters to the configured service.
<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
final class IdentityResolver
{
public function resolve(string $platform, string $url): ResolvedIdentity
{
$started = hrtime(true);
for ($attempt = 1; $attempt <= 2; $attempt++) {
try {
$response = Http::acceptJson()
->connectTimeout(2)
->timeout(4)
->withOptions(['allow_redirects' => false])
->get(config('services.identity_resolver.endpoint'), [
'platform' => $platform,
'url' => $url,
]);
} catch (ConnectionException) {
if ($attempt === 2) {
$this->fail('unavailable', 503);
}
$this->backoff();
continue;
}
$status = $response->status();
if (in_array($status, [502, 503, 504], true)
&& $attempt === 1) {
$this->backoff();
continue;
}
if ($status === 429) {
$this->fail('rate_limited', 503, $status);
}
if (in_array($status, [400, 422], true)) {
$this->fail('rejected', 422, $status);
}
if (! $response->successful()) {
$this->fail('upstream_failure', 503, $status);
}
$body = $response->body();
if (strlen($body) > 65536) {
$this->fail('invalid_response', 502, $status);
}
try {
$payload = json_decode(
$body, false, 32, JSON_THROW_ON_ERROR
);
} catch (\JsonException) {
$this->fail('invalid_response', 502, $status);
}
if (! $payload instanceof \stdClass
|| count((array) $payload) === 0) {
$this->fail('invalid_response', 502, $status);
}
Log::info('identity_resolver.completed', [
'platform' => $platform,
'attempts' => $attempt,
'duration_ms' => (int) ((hrtime(true) - $started) / 1e6),
]);
return new ResolvedIdentity($platform, $payload);
}
throw new \LogicException('Resolver attempt loop exhausted.');
}
private function backoff(): void
{
usleep(random_int(150000, 250000));
}
private function fail(
string $reason,
int $httpStatus,
?int $upstreamStatus = null,
): never {
Log::warning('identity_resolver.failed', [
'reason' => $reason,
'upstream_status' => $upstreamStatus,
]);
throw new ResolverFailure($reason, $httpStatus);
}
}
The network timeout budget is roughly eight seconds plus backoff; configure the surrounding web request timeout accordingly. The size check applies after buffering, not as a streaming download limit. Object validation protects the application’s structural contract; it cannot verify undocumented field semantics.
Validate, normalize, then persist
Create app/Http/Controllers/DirectorySubmissionController.php. There is deliberately no database transaction around the network call. A rejected or unavailable resolution writes nothing; a successful resolution requires one database insert.
<?php
namespace App\Http\Controllers;
use App\Services\IdentityResolver;
use App\Services\ResolverFailure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
final class DirectorySubmissionController extends Controller
{
public function store(
Request $request,
IdentityResolver $resolver,
): JsonResponse {
$input = $request->validate([
'name' => ['required', 'string', 'max:120'],
'platform' => [
'required',
Rule::in(['facebook', 'instagram', 'linkedin']),
],
'profile_url' => ['required', 'url:http,https', 'max:2048'],
]);
try {
$identity = $resolver->resolve(
$input['platform'], $input['profile_url']
);
} catch (ResolverFailure $failure) {
return response()->json(
['error' => $failure->reason],
$failure->httpStatus,
$failure->reason === 'rate_limited'
? ['Retry-After' => '60'] : [],
);
}
$id = DB::table('directory_submissions')->insertGetId([
'name' => $input['name'],
'platform' => $identity->platform,
'normalized_identity' => json_encode(
$identity->publicIdentity, JSON_THROW_ON_ERROR
),
'status' => 'pending',
'created_at' => now(),
'updated_at' => now(),
]);
return response()->json([
'id' => $id,
'status' => 'pending',
'identity' => [
'platform' => $identity->platform,
'public_identity' => $identity->publicIdentity,
],
], 201);
}
}
The 60-second retry hint is an application policy, not a claimed upstream quota or reset time. Clients must also bound their own retries. A lost response after insertion can produce duplicate submissions; this intake permits them for moderation rather than pretending it has identity-level idempotency.
Add these routes to routes/web.php:
use App\Http\Controllers\DirectorySubmissionController;
use Illuminate\Support\Facades\Route;
Route::view('/directory/submit', 'directory-submit');
Route::post('/directory/submissions', [
DirectorySubmissionController::class, 'store',
])->middleware('throttle:directory-submissions');
Replace app/Providers/AppServiceProvider.php with:
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void {}
public function boot(): void
{
RateLimiter::for(
'directory-submissions',
fn (Request $request) => Limit::perMinute(6)
->by($request->ip())
);
}
}
Create resources/views/directory-submit.blade.php. Browser submissions receive Laravel’s normal validation redirects; successful submissions display JSON containing the normalized object.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Submit a directory profile</title>
@foreach ($errors->all() as $error)
<p>{{ $error }}</p>
@endforeach
<form method="post" action="/directory/submissions">
@csrf
<label>Display name
<input name="name" maxlength="120" required>
</label>
<label>Platform
<select name="platform">
<option value="facebook">Facebook</option>
<option value="instagram">Instagram</option>
<option value="linkedin">LinkedIn</option>
</select>
</label>
<label>Profile link
<input type="url" name="profile_url" maxlength="2048" required>
</label>
<button type="submit">Normalize and submit</button>
</form>
</html>
Test behavior without depending on public profiles
Create tests/Feature/DirectorySubmissionTest.php. The synthetic fixture below deliberately claims no real service response fields. These tests verify transport behavior, opaque mapping, persistence, and failure handling.
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
class DirectorySubmissionTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Http::preventStrayRequests();
}
private function input(): array
{
return [
'name' => 'Community workshop',
'platform' => 'instagram',
'profile_url' => 'https://www.instagram.com/instagram/',
];
}
public function test_transient_failure_retries_then_persists(): void
{
$endpoint = config('services.identity_resolver.endpoint');
Http::fake([
$endpoint.'*' => Http::sequence()
->push('', 503)
->push(['synthetic_fixture' => true], 200),
]);
$this->postJson('/directory/submissions', $this->input())
->assertCreated()
->assertJsonPath('status', 'pending')
->assertJsonPath(
'identity.public_identity.synthetic_fixture', true
);
Http::assertSentCount(2);
Http::assertSent(fn (Request $request) =>
$request->method() === 'GET'
&& $request['platform'] === 'instagram'
&& $request['url'] === $this->input()['profile_url']
&& ! $request->hasHeader('Authorization')
);
$stored = DB::table('directory_submissions')->first();
$this->assertTrue(
json_decode($stored->normalized_identity)->synthetic_fixture
);
}
public function test_rate_limit_is_not_retried(): void
{
Http::fake(['*' => Http::response('', 429)]);
$this->postJson('/directory/submissions', $this->input())
->assertStatus(503)
->assertHeader('Retry-After', '60')
->assertJsonPath('error', 'rate_limited');
Http::assertSentCount(1);
$this->assertDatabaseCount('directory_submissions', 0);
}
public function test_array_payload_fails_closed(): void
{
Http::fake(['*' => Http::response('[]', 200)]);
$this->postJson('/directory/submissions', $this->input())
->assertStatus(502)
->assertJsonPath('error', 'invalid_response');
$this->assertDatabaseCount('directory_submissions', 0);
}
public function test_invalid_platform_never_calls_service(): void
{
$input = $this->input();
$input['platform'] = 'unsupported';
$this->postJson('/directory/submissions', $input)
->assertUnprocessable();
Http::assertNothingSent();
}
}
php artisan migrate
DB_CONNECTION=sqlite DB_DATABASE=:memory: php artisan test --filter=DirectorySubmissionTest
php artisan serve
Deploy with explicit operational boundaries
Serve Laravel through its public directory with HTTPS and APP_DEBUG=false. Keep SQLite on durable storage with backups for a single-instance deployment. Multiple replicas should use a shared relational database, including shared database-backed cache and sessions. Configure trusted proxies correctly so the IP limiter sees the intended client address.
During deployment, run php artisan migrate --force and php artisan config:cache. Reload long-lived application workers after configuration changes. Keep the resolver endpoint deployment-controlled; never accept it from a request.
Logs expose failure categories, upstream status, attempts, and successful-call duration without recording profile URLs, response bodies, or credentials. Monitor failure counts and latency trends. Investigate persistent 401 or 403 responses against the documentation instead of adding guessed authentication.
Common failures have distinct remedies: local 419 responses indicate session or CSRF trouble; upstream rejection means checking the submitted platform and supported reference; repeated 429 responses require reducing traffic; malformed successful responses require checking the documented response shape. Never convert these conditions into successful directory entries.
Treat stored objects as untrusted data. Escape any future presentation, allowlist link schemes and hosts before rendering clickable destinations, restrict moderation access, and define retention for abandoned submissions.
Verify the complete intake path
- Open
/directory/submitand submit a supported link for each platform. - Confirm HTTP 201, a normalized response object, and one pending database row.
- Confirm invalid input writes nothing and makes no external request.
- Run the automated retry, rate-limit, malformed-response, and persistence checks.
- Verify production logs omit submitted references and response bodies.
- Confirm publishing requires a separate authorized moderation decision.
The useful result is a narrow, dependable boundary: directory links enter as messy references and leave as resolver-owned identity objects. Keeping normalization separate from ownership, deduplication, and publication makes the feature easier to operate today and safer to extend tomorrow.