# Laravel quickstart

> A Laravel website that shows every CMS Orbit page at its own address with Blade templates, previews drafts in the editor and refreshes its cache when editors publish.

Source: https://docs.bifrostorbit.com/cms/developers/quickstart-laravel/

This guide builds a Laravel website for Northwilds that reads its pages from CMS Orbit with the PHP SDK, `bifrost-orbit/cms-sdk`. Every page an editor publishes appears at its own address, each component is drawn by a Blade template, editors see their drafts in the live preview, and a signed webhook clears the cache when they publish.

Tested with Laravel 13.40, PHP 8.5, Composer 2.10 and `bifrost-orbit/cms-sdk` 0.2.0.

Prefer to start from a working project? Use the starter: [bifrost-orbit/cms-starter-laravel](https://github.com/bifrost-orbit/cms-starter-laravel), the finished code of this guide.

## Before you start

You need:

- **PHP 8.1 or later and Composer.**
- **A CMS Orbit space** with at least one published page, such as the home page at `/`.
- **Two keys** from **Configuration › API keys**: a public `cms_pk_` key for published content and a secret `cms_sk_` key with **Read drafts** on, from Staging. Step 4 of [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/) shows how to create them.
- **The API address and the region key.** The address is `https://api.bifrostorbit.com/cms`. The region key, such as `germany`, is in **Configuration › Environments**. See step 3 of [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/).

## 1. Create the project

```bash
composer create-project laravel/laravel northwilds
cd northwilds
```

## 2. Install the SDK

```bash
composer require bifrost-orbit/cms-sdk:^0.2
```

## 3. Add the settings

Add the keys to `.env`:

```bash
# .env
CMS_API_URL=https://api.bifrostorbit.com/cms
CMS_PUBLIC_KEY=cms_pk_…
CMS_PREVIEW_KEY=cms_sk_…
CMS_WEBHOOK_SECRET=whsec_…
CMS_DEFAULT_REGION=germany
```

`CMS_WEBHOOK_SECRET` comes in step 8. Read the settings in `config/services.php`, inside the array it returns:

```php
// config/services.php
'cms' => [
    'url' => env('CMS_API_URL'),
    'key' => env('CMS_PUBLIC_KEY'),
    'preview_key' => env('CMS_PREVIEW_KEY'),
    'webhook_secret' => env('CMS_WEBHOOK_SECRET'),
    'region' => env('CMS_DEFAULT_REGION'),
],
```

Give CMS answers their own cache store, so the webhook can clear them without touching the rest of your cache. Laravel's default `file` and `database` stores cannot hold cache tags, so this guide empties the whole store when editors publish; step 8 shows how to clear only what changed with Redis. Add the store to `stores` in `config/cache.php`:

```php
// config/cache.php
'cms' => [
    'driver' => 'file',
    'path' => storage_path('framework/cache/cms'),
],
```

## 4. Create the client

Register the client and the component renderer as singletons. The renderer has no templates yet, so every component goes to the fallback:

```php
// app/Providers/AppServiceProvider.php
<?php

namespace App\Providers;

use BifrostOrbit\Cms\BlockRenderer;
use BifrostOrbit\Cms\Client;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(Client::class, fn () => new Client(
            apiKey: config('services.cms.key'),
            baseUrl: config('services.cms.url'),
            previewKey: config('services.cms.preview_key'),
            defaultRegion: config('services.cms.region'),
        ));

        $this->app->singleton(BlockRenderer::class, fn () => new BlockRenderer(
            [],
            fn (array $block) => view('blocks.unknown', ['block' => $block])->render(),
        ));
    }
}
```

```blade
{{-- resources/views/blocks/unknown.blade.php --}}
@if (config('app.debug'))
    <section data-cms-id="{{ $block['id'] }}">
        <p>No template for the {{ $block['type'] }} component yet.</p>
    </section>
@endif
```

The fallback names the component while `APP_DEBUG` is on, and prints nothing on the live website.

## 5. Show a page

One catch-all route sends every address to the controller:

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

use App\Http\Controllers\PageController;
use Illuminate\Support\Facades\Route;

Route::get('/{path?}', [PageController::class, 'show'])->where('path', '.*');
```

The controller asks CMS Orbit what the address is with `resolve`, and keeps the answer for 60 seconds:

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

namespace App\Http\Controllers;

use BifrostOrbit\Cms\BlockRenderer;
use BifrostOrbit\Cms\Client;
use Illuminate\Support\Facades\Cache;

class PageController extends Controller
{
    public function show(Client $cms, BlockRenderer $blocks, ?string $path = null)
    {
        $path = '/' . $path;
        $result = Cache::store('cms')->remember('page:' . $path, 60, fn () => $cms->resolve($path));

        return match ($result['kind']) {
            'redirect' => redirect($result['to'], $result['status']),
            'gone' => abort(410),
            'notFound' => abort(404),
            'page' => view('page', ['page' => $result['page'], 'blocks' => $blocks]),
        };
    }
}
```

A moved page redirects with the status the editor chose, a deleted one answers `410`, and an unknown address shows Laravel's 404 page. The layout prints the page's title, description, canonical address, share tags and structured data with `Seo`:

```blade
{{-- resources/views/page.blade.php --}}
@use('BifrostOrbit\Cms\Seo')
<!DOCTYPE html>
<html lang="{{ $page['locale'] }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {!! Seo::headTags($page) !!}
    {!! Seo::jsonLd($page) !!}
</head>
<body>
    <main>
        {!! $blocks->render($page['components']) !!}
    </main>
</body>
</html>
```

Run `php artisan serve` and open `http://localhost:8000`. The page has its title, and each component shows "No template for the hero component yet". An address that is not in CMS Orbit, such as `/no-such-page`, answers `404`.

## 6. Write and register components

Each component arrives with `id`, `type`, `fields` and `children`. Here are templates for a hero with two buttons and a feature grid with its items. Your space's components and fields may have other names: see them in **Configuration › Components**.

```blade
{{-- resources/views/blocks/hero.blade.php --}}
@php($f = $block['fields'])
<section class="hero" data-cms-id="{{ $block['id'] }}">
    @if (!empty($f['eyebrow']))
        <p class="eyebrow">{{ $f['eyebrow'] }}</p>
    @endif
    <h1>{{ $f['heading'] ?? '' }}</h1>
    {!! $f['description'] ?? '' !!}
    <div class="actions">
        {!! $blocks->renderOne($f['primaryAction'] ?? null) !!}
        {!! $blocks->renderOne($f['secondaryAction'] ?? null) !!}
    </div>
</section>
```

```blade
{{-- resources/views/blocks/action.blade.php --}}
@php($f = $block['fields'])
<a class="button {{ $f['style'] ?? '' }}" href="{{ $f['link']['href'] ?? '#' }}" data-cms-id="{{ $block['id'] }}">
    {{ $f['label'] ?? '' }}
</a>
```

```blade
{{-- resources/views/blocks/feature-grid.blade.php --}}
@php($f = $block['fields'])
<section class="feature-grid" data-cms-id="{{ $block['id'] }}">
    <h2>{{ $f['heading'] ?? '' }}</h2>
    @if (!empty($f['intro']))
        <p>{{ $f['intro'] }}</p>
    @endif
    <div class="grid">
        {!! $blocks->slot($block, 'items') !!}
    </div>
</section>
```

```blade
{{-- resources/views/blocks/feature-item.blade.php --}}
@php($f = $block['fields'])
<article data-cms-id="{{ $block['id'] }}">
    <h3>{{ $f['title'] ?? '' }}</h3>
    <p>{{ $f['body'] ?? '' }}</p>
    @if (!empty($f['link']['href']))
        <a href="{{ $f['link']['href'] }}">Read more</a>
    @endif
</article>
```

Rich text, such as the hero's `description`, arrives as HTML, so print it with `{!! !!}`. Everything else goes through `{{ }}`. A block in a single slot, such as a button, is on its field, so `renderOne` draws it. `slot` draws the list of blocks in a Components slot, such as the grid's items.

Register the templates by component key. Replace `app/Providers/AppServiceProvider.php` with:

```php
// app/Providers/AppServiceProvider.php
<?php

namespace App\Providers;

use BifrostOrbit\Cms\BlockRenderer;
use BifrostOrbit\Cms\Client;
use Closure;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(Client::class, fn () => new Client(
            apiKey: config('services.cms.key'),
            baseUrl: config('services.cms.url'),
            previewKey: config('services.cms.preview_key'),
            defaultRegion: config('services.cms.region'),
        ));

        $this->app->singleton(BlockRenderer::class, fn () => new BlockRenderer(
            [
                'hero' => self::template('blocks.hero'),
                'featureGrid' => self::template('blocks.feature-grid'),
                'featureItem' => self::template('blocks.feature-item'),
                'action' => self::template('blocks.action'),
            ],
            fn (array $block) => view('blocks.unknown', ['block' => $block])->render(),
        ));
    }

    private static function template(string $view): Closure
    {
        return fn (array $block, BlockRenderer $blocks) => view($view, ['block' => $block, 'blocks' => $blocks])->render();
    }
}
```

Reload the page: the hero is drawn by your template, and the fallback names the components still to write.

## 7. Preview drafts in the editor

The editor opens your website at the space's **Preview URL** followed by the page's address and `?preview=<token>`. The controller checks the token, sets a cookie and sends the editor to the page. While the cookie is there, it reads drafts with the secret key and never caches them. Replace the controller with:

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

namespace App\Http\Controllers;

use BifrostOrbit\Cms\BlockRenderer;
use BifrostOrbit\Cms\Client;
use BifrostOrbit\Cms\Preview;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class PageController extends Controller
{
    public function show(Request $request, Client $cms, BlockRenderer $blocks, ?string $path = null)
    {
        $path = '/' . $path;

        if ($request->filled('preview')) {
            $token = $cms->verifyPreviewToken($request->query('preview'));
            abort_if($token === null, 401, 'That preview link is invalid or has expired');

            return redirect(Preview::redirectPath($path, $token))
                ->withCookie(cookie('cms_preview', '1', 0, '/', null, true, true, false, 'none'));
        }

        $preview = $request->cookie('cms_preview') === '1';
        $result = $preview
            ? $cms->resolve($path, ['preview' => true])
            : Cache::store('cms')->remember('page:' . $path, 60, fn () => $cms->resolve($path));

        return match ($result['kind']) {
            'redirect' => redirect($result['to'], $result['status']),
            'gone' => abort(410),
            'notFound' => abort(404),
            'page' => response()
                ->view('page', ['page' => $result['page'], 'blocks' => $blocks, 'cms' => $cms, 'preview' => $preview])
                ->header('Cache-Control', $preview ? 'no-store' : 'public, max-age=60'),
        };
    }
}
```

Then add the bridge script to `resources/views/page.blade.php`. Add `@use('BifrostOrbit\Cms\Preview')` at the top, and this just before `</body>`:

```blade
@if ($preview)
    {!! Preview::bridgeScript($cms) !!}
@endif
```

`Preview::redirectPath` only ever sends the editor to an address on your own website. The bridge lets editors click a component to select it, through the `data-cms-id` on each template's outer element, and reloads the preview after each save.

The cookie is `Secure` with `SameSite=None`, so the browser keeps it inside the editor's frame. Serve the preview website over `https`, and set its address as the **Preview URL** in the space's **Settings**. See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/).

## 8. Refresh when editors publish

Create a webhook in **Configuration › Webhooks** with the address `https://<your website>/cms-webhook`, and put its secret in `CMS_WEBHOOK_SECRET`. See [Refresh the website when content changes](https://docs.bifrostorbit.com/cms/developers/webhooks/).

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

namespace App\Http\Controllers;

use BifrostOrbit\Cms\Webhook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CmsWebhookController extends Controller
{
    public function __invoke(Request $request)
    {
        $message = Webhook::parse(config('services.cms.webhook_secret'), $request->headers->all(), $request->getContent());

        if ($message === null) {
            return response()->noContent(401);
        }

        if (Webhook::tagsForEvent($message['event'], $message['data']) !== []) {
            Cache::store('cms')->flush();
        }

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

`Webhook::parse` checks the signature against the raw body and refuses messages more than five minutes old. A test message from **Send a test** has no tags, so it answers `204` and clears nothing. Any other change clears the `cms` store, and the next visitor gets fresh content.

Add the route before the catch-all:

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

use App\Http\Controllers\CmsWebhookController;
use App\Http\Controllers\PageController;
use Illuminate\Support\Facades\Route;

Route::post('/cms-webhook', CmsWebhookController::class);

Route::get('/{path?}', [PageController::class, 'show'])->where('path', '.*');
```

CMS Orbit cannot send a CSRF token, so leave the webhook out of the check in `bootstrap/app.php`:

```php
// bootstrap/app.php
->withMiddleware(function (Middleware $middleware): void {
    $middleware->preventRequestForgery(except: ['cms-webhook']);
})
```

On Laravel 12, the method is called `validateCsrfTokens`.

A correctly signed message answers `204`, and one with a wrong signature or an old timestamp answers `401`.

### Clear only what changed, with Redis

A store that holds tags, such as Redis or Memcached, can keep each page under the same tags as the JavaScript SDK, such as `cms:page:germany:/pricing`, so publishing one page clears only that page. With Redis set up as in [Laravel's cache documentation](https://laravel.com/docs/cache#redis), point the `cms` store at it in `config/cache.php`:

```php
// config/cache.php
'cms' => [
    'driver' => 'redis',
    'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
],
```

In the controller, store each page under `CacheTags::ALL` and its own tag. Add `use BifrostOrbit\Cms\CacheTags;` and replace the cached read with:

```php
$tags = [CacheTags::ALL, CacheTags::page(config('services.cms.region'), $path)];
$result = $preview
    ? $cms->resolve($path, ['preview' => true])
    : Cache::store('cms')->tags($tags)->remember('page:' . $path, 60, fn () => $cms->resolve($path));
```

In the webhook, flush only the tags `tagsForEvent` returns:

```php
$tags = Webhook::tagsForEvent($message['event'], $message['data']);
if ($tags !== []) {
    Cache::store('cms')->tags($tags)->flush();
}
```

A change that can touch every page, such as a shared section or a page moved to a new address, returns `cms` and clears them all. See [Caching and refreshing pages](https://docs.bifrostorbit.com/cms/developers/caching-and-refresh/).

## Next steps

- [The PHP SDK](https://docs.bifrostorbit.com/cms/developers/sdk-php/): every client method, menus, global content, lists, images, errors and tests
- [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/): fields, images, links, slots and variants
- [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/): what the editor needs from your website
- [Refresh the website when content changes](https://docs.bifrostorbit.com/cms/developers/webhooks/): events and what each one carries
- [Regions and languages](https://docs.bifrostorbit.com/cms/developers/regions-and-languages/): show more than one region or language
- [Metadata, sitemaps and robots with the SDK](https://docs.bifrostorbit.com/cms/developers/seo-with-the-sdk/): sitemaps, robots.txt and structured data
- [Troubleshooting your website](https://docs.bifrostorbit.com/cms/developers/troubleshooting/): when a page, the preview or a webhook does not work
