# Laravel

Read Mojimoto content from a Laravel app with the HTTP client, cache it, and clear the cache when a webhook reports a publish.

There is no Mojimoto package for Laravel to install yet. You do not need one to read content. The [Delivery API](/docs/api/delivery) is JSON over HTTPS, and Laravel's HTTP client reads it in a few lines.

This page shows the parts most sites need: configuration, a small client, caching, a webhook that clears the cache, drafts and rich text.

## Configure

```env .env
MOJIMOTO_ENDPOINT=https://mojimoto.com/api/v1
MOJIMOTO_PROJECT=acme
MOJIMOTO_TOKEN=mjmt_your_read_token
MOJIMOTO_WEBHOOK_SECRET=your-webhook-secret
```

```php config/services.php
'mojimoto' => [
    'endpoint' => env('MOJIMOTO_ENDPOINT', 'https://mojimoto.com/api/v1'),
    'project' => env('MOJIMOTO_PROJECT'),
    'token' => env('MOJIMOTO_TOKEN'),
    'webhook_secret' => env('MOJIMOTO_WEBHOOK_SECRET'),
],
```

These names are your own. The token needs the `read` ability.

## Write a small client

The token goes in the `Authorization` header as a Bearer token. Every response is cached for an hour under a key that includes a generation number, so one call to `flush` makes the app ignore all of them.

```php app/Services/Mojimoto.php
<?php

namespace App\Services;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class Mojimoto
{
    /**
     * @param  array<string, mixed>  $query
     * @return array<string, mixed>
     */
    public function documents(array $query = []): array
    {
        $key = 'mojimoto:'.$this->generation().':'.sha1(json_encode($query));

        return Cache::remember($key, now()->addHour(), fn () => $this->fetch($query));
    }

    /**
     * @param  array<string, mixed>  $query
     * @return array<string, mixed>|null
     */
    public function byUid(string $type, string $uid, array $query = []): ?array
    {
        $entries = $this->documents([...$query, 'type' => $type, 'uid' => $uid, 'per_page' => 1]);

        return $entries['results'][0] ?? null;
    }

    /**
     * @param  array<string, mixed>  $query
     * @return array<string, mixed>
     */
    public function fetch(array $query = []): array
    {
        return $this->request()->get('documents', $query)->throw()->json();
    }

    public function flush(): void
    {
        Cache::forever('mojimoto:generation', $this->generation() + 1);
    }

    private function generation(): int
    {
        return (int) Cache::get('mojimoto:generation', 1);
    }

    private function request(): PendingRequest
    {
        $endpoint = config('services.mojimoto.endpoint');
        $project = config('services.mojimoto.project');

        return Http::baseUrl("{$endpoint}/{$project}")
            ->withToken(config('services.mojimoto.token'))
            ->acceptJson();
    }
}
```

`throw()` raises a `RequestException` for any 4xx or 5xx. The API's error body is `{ "message": "..." }`. Every status is on the [Errors](/docs/api/errors) page.

## Fetch entries

```php app/Http/Controllers/PostController.php
<?php

namespace App\Http\Controllers;

use App\Services\Mojimoto;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PostController extends Controller
{
    public function index(Request $request, Mojimoto $mojimoto): View
    {
        $posts = $mojimoto->documents([
            'type' => 'post',
            'sort' => '-updated_at',
            'per_page' => 10,
            'page' => $request->integer('page', 1),
        ]);

        return view('posts.index', [
            'posts' => $posts['results'],
            'totalPages' => $posts['total_pages'],
        ]);
    }

    public function show(Mojimoto $mojimoto, string $uid): View
    {
        $post = $mojimoto->byUid('post', $uid, ['depth' => 2]);

        abort_if($post === null, 404);

        return view('posts.show', ['post' => $post]);
    }
}
```

A list response has `results`, `page`, `per_page`, `total_results`, `total_pages`, `lang` and `ref`. Each entry has `id`, `uid`, `type`, `lang`, `status`, `published_at`, `updated_at` and `data`, which holds your fields.

| Parameter | Example | Description |
| --- | --- | --- |
| `type` | `'post'` | Only entries of this content type. |
| `uid` | `'hello-world'` | Only the entry with this UID. |
| `lang` | `'fr-fr'` | The locale. The project's default when left out. |
| `page`, `per_page` | `2`, `10` | Paging. `per_page` defaults to 20 and stops at 100. |
| `sort` | `'-updated_at'` | `id`, `uid`, `created_at`, `updated_at`, or a field as `fields.price`. `-` in front for descending. |
| `depth` | `2` | How many levels of linked entries to include, from 1 to 3. |
| `fields.{field}` | `'fields.category' => 'news'` | Filter on a field. For an operator, pass an array: `'fields.price' => ['gte' => 10]`. Needs `type`. |
| `select` | `'fields.title,fields.cover'` | Return only these fields. |

The [Delivery API reference](/docs/api/delivery) has every parameter and operator.

A `media` field is an object with `url`, `alt`, `width` and `height`, and a `reference` field is the linked entry itself:

```php resources/views/posts/show.blade.php
<article>
    <h1>{{ $post['data']['title'] }}</h1>

    @if ($cover = $post['data']['cover'] ?? null)
        <img src="{{ $cover['url'] }}" alt="{{ $cover['alt'] ?? '' }}" width="{{ $cover['width'] }}" height="{{ $cover['height'] }}">
    @endif

    @if ($author = $post['data']['author'] ?? null)
        <p>By {{ $author['data']['name'] ?? '' }}</p>
    @endif
</article>
```

## Clear the cache on publish

Add a [webhook](/docs/concepts/webhooks) in your project that posts to your app, and verify its signature before you act on it. The signature is `sha256=` followed by the HMAC-SHA256 of the raw request body, keyed with the webhook's secret.

```php routes/api.php
use App\Services\Mojimoto;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/webhooks/mojimoto', function (Request $request, Mojimoto $mojimoto) {
    $secret = config('services.mojimoto.webhook_secret');

    $expected = 'sha256='.hash_hmac('sha256', $request->getContent(), $secret);

    $signature = (string) $request->header('X-Mojimoto-Signature');

    abort_unless(hash_equals($expected, $signature), 401);

    $mojimoto->flush();

    return response()->noContent();
});
```

Register the route where CSRF protection does not apply. In `routes/api.php` its URL is `/api/webhooks/mojimoto`. The body is JSON with `event`, `project` and `document`, and `event` is `document.published`, `document.unpublished` or `document.deleted`.

## Read drafts

Add `'ref' => 'preview'` to get the newest version of each entry, published or not. The token needs the `preview` ability. Without it the API returns published content and no error.

```php
$draft = $mojimoto->fetch(['type' => 'page', 'uid' => 'home', 'ref' => 'preview'])['results'][0] ?? null;
```

Call `fetch` for drafts, not `documents`, so they are never cached. See the [Preview API](/docs/api/preview).

## Render rich text

A `rich_text` field is an array of blocks, not HTML. There is no PHP renderer to install yet, so walk the blocks yourself. The [Rich text](/docs/frameworks/rich-text) page lists every block and span.

```php resources/views/partials/rich-text.blade.php
@foreach ($blocks ?? [] as $block)
    @switch($block['type'])
        @case('heading2')
            <h2>{{ $block['text'] }}</h2>
            @break

        @case('image')
            <img src="{{ $block['url'] }}" alt="{{ $block['alt'] ?? '' }}">
            @break

        @default
            <p>{{ $block['text'] ?? '' }}</p>
    @endswitch
@endforeach
```

This prints the text of each block and leaves out bold, italic and links. Those are in each block's `spans`, as `start` and `end` positions counted in UTF-16 code units. Convert the text with `mb_convert_encoding($text, 'UTF-16BE', 'UTF-8')` before you cut it, or any character outside the basic plane, such as an emoji, will shift everything after it.
