# Quickstart: Laravel (PHP)
Source: https://sovaria.in/docs/quickstart-laravel

Use Sovaria from Laravel over the REST API: sign users up and in, keep their tokens in the Laravel session, and read and add their own notes with Laravel's HTTP client.

There is no PHP SDK yet; Laravel's HTTP client and Sovaria's REST API are all you need. Users sign up and in through your Laravel app, their Sovaria tokens stay on your server, encrypted in Laravel's cache under the session id (the browser only gets the session cookie), and every query runs **as that user**, so your row rules apply on the server too. Your app never holds a key that bypasses them.

## Before you start

Do steps 1 to 3 of the [Quickstart](https://sovaria.in/docs/quickstart) first: create a project, copy its **project URL** and **anon key** ([Quickstart](https://sovaria.in/docs/quickstart#connect)), and create the `notes` table with its row rules ([Quickstart](https://sovaria.in/docs/quickstart#table)). Every signed-in user then sees and changes only their own notes, whatever the app code does.

## 1. Configuration

.env:
```bash
SOVARIA_URL=https://<project-ref>.sovarias.in
SOVARIA_ANON_KEY=<anon-key>
CACHE_STORE=redis             # or database: the token pair lives here (shared by every server)
SESSION_SECURE_COOKIE=true    # production
```

config/services.php:
```text
'sovaria' => [
    'url' => env('SOVARIA_URL'),
    'anon_key' => env('SOVARIA_ANON_KEY'),
],
```

## 2. A small client

app/Services/Sovaria.php:
```text
<?php

namespace App\Services;

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class Sovaria
{
    /** Requests as the anon key (sign-up, sign-in) or as the signed-in user (their access token). */
    public function http(?string $accessToken = null): PendingRequest
    {
        $request = Http::baseUrl(config('services.sovaria.url'))
            ->withHeaders(['apikey' => config('services.sovaria.anon_key')])
            ->acceptJson()
            ->timeout(10);

        return $accessToken ? $request->withToken($accessToken) : $request;
    }

    /** Creates the user. True when the project asks people to confirm their email before they can sign in. */
    public function signUp(string $email, string $password): bool
    {
        $user = $this->http()->post('/api/v1/auth/register', compact('email', 'password'))->throw()->json();
        return (bool) ($user['email_verification_required'] ?? false);
    }

    /** Signs in and keeps the token pair for this browser session. Call after session()->regenerate(). */
    public function signIn(string $email, string $password): void
    {
        // A fresh random name for this sign-in's token pair, kept in the session: once the session expires or is
        // invalidated, nothing points at the pair any more, even if an old session cookie comes back.
        session()->put('sovaria_pair', Str::random(40));
        $this->store($this->http()->post('/api/v1/auth/project/login', compact('email', 'password'))->throw()->json());
    }

    public function signOut(): void
    {
        if ($tokens = $this->tokens()) {
            $this->http($tokens['access_token'])->post('/api/v1/auth/logout', ['refresh_token' => $tokens['refresh_token']]);
        }
        if ($key = $this->key()) {
            Cache::forget($key);
        }
        session()->forget('sovaria_pair');
    }

    /**
     * Runs $call with the user's access token. Access tokens last 15 minutes: on a 401 the refresh token is traded for
     * a new pair. Refresh tokens rotate (each works once), so the pair lives in the cache, read and written under a
     * lock: a second request waiting on the lock finds the new pair and reuses it instead of refreshing again.
     */
    public function asUser(callable $call): mixed
    {
        $tokens = $this->tokens() ?? $this->signedOut();
        try {
            return $call($this->http($tokens['access_token']));
        } catch (RequestException $e) {
            if ($e->response->status() !== 401) throw $e;
        }
        $tokens = Cache::lock($this->key().':lock', 10)->block(5, function () use ($tokens) {
            $current = $this->tokens();
            if ($current && $current['access_token'] !== $tokens['access_token']) {
                return $current;                       // another request already refreshed
            }
            $fresh = $this->http()->post('/api/v1/auth/refresh', ['refresh_token' => $tokens['refresh_token']]);
            if ($fresh->failed()) {
                Cache::forget($this->key());           // revoked or expired: sign in again
                $this->signedOut();
            }
            $this->store($fresh->json());
            return $fresh->json();
        });
        return $call($this->http($tokens['access_token']));
    }

    private function key(): ?string
    {
        $name = session('sovaria_pair');
        return $name ? 'sovaria-tokens:'.$name : null;   // no marker in this session: signed out
    }

    private function tokens(): ?array
    {
        $key = $this->key();
        $sealed = $key ? Cache::get($key) : null;
        if (! $sealed) {
            return null;
        }
        try {
            return json_decode(Crypt::decryptString($sealed), true);
        } catch (DecryptException) {
            Cache::forget($key);                       // APP_KEY was rotated: sign in again
            return null;
        }
    }

    private function store(array $tokens): void
    {
        // Encrypted with APP_KEY. Kept no longer than an idle session lives; each refresh (at least every
        // 15 minutes of use) writes it again.
        Cache::put($this->key(), Crypt::encryptString(json_encode($tokens)),
            now()->addMinutes(config('session.lifetime', 120)));
    }

    private function signedOut(): never
    {
        throw new HttpResponseException(redirect('/')->with('status', 'Please sign in again.'));
    }
}
```

## 3. Routes

routes/web.php:
```text
<?php

use App\Services\Sovaria;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/signup', function (Request $r, Sovaria $sov) {
    $data = $r->validate(['email' => 'required|email', 'password' => 'required|min:8']);
    if ($sov->signUp($data['email'], $data['password'])) {
        return redirect('/')->with('status', 'Check your inbox to confirm your email, then sign in.');
    }
    $r->session()->regenerate();
    $sov->signIn($data['email'], $data['password']);
    return redirect('/notes');
});

Route::post('/signin', function (Request $r, Sovaria $sov) {
    $data = $r->validate(['email' => 'required|email', 'password' => 'required']);
    $r->session()->regenerate();
    $sov->signIn($data['email'], $data['password']);
    return redirect('/notes');
});

Route::get('/notes', function (Sovaria $sov) {
    // PostgREST-style read; the row rules return only this user's notes.
    $notes = $sov->asUser(fn ($http) => $http
        ->get('/rest/v1/notes', ['select' => 'id,body,created_at', 'order' => 'id.desc'])
        ->throw()->json());
    return view('notes', ['notes' => $notes]);
});

Route::post('/notes', function (Request $r, Sovaria $sov) {
    $body = $r->validate(['body' => 'required|string|max:2000'])['body'];
    $sov->asUser(fn ($http) => $http
        ->withHeaders(['Prefer' => 'return=minimal'])
        ->post('/rest/v1/notes', ['body' => $body])
        ->throw());
    return redirect('/notes');
});

Route::post('/signout', function (Request $r, Sovaria $sov) {
    $sov->signOut();
    $r->session()->invalidate();
    return redirect('/');
});
```

- The `owner_id` column fills itself in (`default auth.uid()`), so the insert sends only `body`, and the row rule refuses anything else.
- The token pair is kept in the cache, encrypted with your `APP_KEY`, under a random name the session holds (so an expired session can't reach it), for no longer than the session lifetime: not in the session itself, because a session is loaded once per request and two requests would each refresh with the same single-use refresh token. The cache lock makes the second request reuse the first one's new pair.
- Use a shared cache (`CACHE_STORE=redis` or `database`) whenever more than one server or worker handles requests.
- Server-to-server calls send no browser `Origin`, so allowed origins don't apply. The REST API is described in [HTTP API](https://sovaria.in/docs/http-api) and its OpenAPI file.
- Need to act as your app rather than a user (a queue job, a webhook)? Use the service role key from your secret store in a separate client, on the server only: it bypasses every rule ([API keys](https://sovaria.in/docs/api-keys)).

## 4. A view

resources/views/notes.blade.php:
```text
<form method="post" action="/notes">
    @csrf
    <input name="body" maxlength="2000" required placeholder="Write a note">
    <button>Add</button>
</form>
<ul>
    @foreach ($notes as $note)
        <li>{{ $note['body'] }}</li>
    @endforeach
</ul>
<form method="post" action="/signout">@csrf <button>Sign out</button></form>
```

## Next steps

- Check who can read and change `notes` before you ship: [Tutorial: prove your table is private before you ship](https://sovaria.in/docs/tutorial-secure-a-table).
- Push new notes to other devices as they happen: [Database change events](https://sovaria.in/docs/realtime-database-changes).
- Every REST route: [HTTP API](https://sovaria.in/docs/http-api).
- Rather describe a whole app and have Sovariq build the pages, tables and rules? [Tutorial: build your first app with Sovariq](https://sovaria.in/docs/tutorial-build-first-app).
