PagibleAI PHP API for Laravel Developers

Your Laravel application can create, change and publish content of PagibleAI CMS in PHP, e.g. in commands, jobs, seeders or payment webhooks. The facades in Aimeos\Cms\Facades do the same as the admin panel, GraphQL and MCP: they create versions, check permissions, update the search index, invalidate caches and dispatch events. Don't save the models directly, because all of this would be skipped.

The facades are available since PagibleAI 0.14.

Where to start:

Facades

Facade
Operations
Pages
add, save, bulk, move, copy, publish, drop, restore, purge
Variants
add, save, revert, bulk, publish, translate, setSource, ignore, drop, restore, purge for the language variants of pages
Elements
add, save, bulk, publish, drop, restore, purge for shared elements
Files
add, save, bulk, relocate, publish, drop, restore, purge
use Aimeos\Cms\Facades\Pages;
use Aimeos\Cms\Facades\Variants;
use Aimeos\Cms\Models\PageView;

// ID of an existing page to add the new page below, e.g. found by its tag
$rootId = PageView::where( 'tag', 'root' )->value( 'id' );

// each call returns the changed PageView
$page = Pages::add( ['name' => 'About', 'path' => 'about', 'lang' => 'en'], $user, parent: $rootId );
$page = Pages::save( $page->id, ['title' => 'About us'], $user );
$page = Pages::publish( $page->id, $user );

// these return the German PageView
$de = Variants::add( $page->id, 'de', $user );
$de = Variants::save( $page->id, 'de', ['title' => 'Über uns'], $user );
$de = Variants::publish( $page->id, 'de', $user );

New pages are inactive until they are published. The status passed to Pages::add() is stored in the draft and applied by publish(). If you don't pass a path, it's generated from the title, and a missing domain, theme or type is taken from the parent page. That's why the short example above works.

save() only changes the keys you pass and keeps the others from the latest draft. A passed content replaces the complete list of content elements, so always pass all elements of the page.

Pages::save(), bulk() and publish() change the source language of a page. The methods with the same names in Variants change the language you pass. Variants::revert() saves the content of an old version like save() and marks the translation as "Needs update". See Multilingual Websites for how languages work.

Method signatures

The single-item methods return the changed PageView, Element or File model, the Many methods a collection of them and bulk() a BulkResult. ?User stands for ?Illuminate\Contracts\Auth\Authenticatable and a|b for methods with the same arguments.

Pages::add( array $input, ?User $user = null, ?string $ref = null, ?string $parent = null, bool $sections = false )
Pages::save( string $id, array $input, ?User $user = null, ?string $latestId = null )
Pages::bulk( array $ids, array $input, ?User $user = null, bool $descendants = false )
Pages::move|copy( string $id, ?User $user = null, ?string $ref = null, ?string $parent = null )
Pages::publish( string $id, ?User $user = null, ?string $at = null )
Pages::publishMany( array $ids, ?User $user = null, ?string $at = null )
Pages::drop|restore|purge( string $id, ?User $user = null )
Pages::dropMany|restoreMany|purgeMany( array $ids, ?User $user = null, array $fields = [] )

Variants::add( string $id, string $lang, ?User $user = null )
Variants::save|revert( string $id, string $lang, array $input, ?User $user = null, ?string $latestId = null )
Variants::bulk( array $ids, string $lang, array $input, ?User $user = null, bool $descendants = false )
Variants::publish( string $id, string $lang, ?User $user = null, ?string $at = null )
Variants::publishMany( array $ids, string $lang, ?User $user = null, ?string $at = null )
Variants::translate( string $id, string $lang, ?User $user = null, ?callable $translate = null )
Variants::setSource|ignore|drop|restore|purge( string $id, string $lang, ?User $user = null )
Variants::ignoreMany|dropMany|restoreMany|purgeMany( array $ids, string $lang, ?User $user = null, array $fields = [] )

Elements::add( array $input, ?User $user = null )
Elements::save( string $id, array $input, ?User $user = null, ?string $latestId = null )
Elements::bulk( array $ids, array $input, ?User $user = null )

Files::add( UploadedFile|string $source, array $input = [], ?User $user = null, ?string $disk = null, ?UploadedFile $preview = null )
Files::save( string $id, array $input, ?User $user = null, ?string $latestId = null, ?UploadedFile $upload = null, UploadedFile|false|null $preview = null )
Files::bulk( array $ids, array $input, ?User $user = null )
Files::relocate( string $id, string $disk, ?User $user = null )
Files::relocateMany( array $ids, string $disk, ?User $user = null )

// Elements and Files, like Pages
publish( string $id, ?User $user = null, ?string $at = null )
publishMany( array $ids, ?User $user = null, ?string $at = null )
drop|restore|purge( string $id, ?User $user = null )
dropMany|restoreMany|purgeMany( array $ids, ?User $user = null, array $fields = [] )

Input fields

Pages::add(), save() and bulk() as well as Variants::save() and bulk() accept these keys, all optional:

Key
Content
lang
Language code, e.g. en or en-GB; only for add(), defaults to the app locale
name
Short name shown in the navigation
title
Page title for the browser and search engines
path
URL path, unique per domain
domain
Domain of the page, empty for all domains
to
URL the page redirects to
tag
Tag to find a page, e.g. the start of a navigation
theme
Theme name, empty for the default cms theme
type
Page type of the theme, e.g. page, blog or docs
status
0 inactive, 1 visible, 2 hidden in the navigation
cache
Cache lifetime in minutes
content
List of content elements, e.g. ['type' => 'text', 'group' => 'main', 'data' => ['text' => 'Hello']]; missing id and group values are generated and the data is validated against the schema.json of the themes
meta, config
Entries keyed by their type, e.g. ['meta-tags' => ['type' => 'meta-tags', 'data' => [...]]]

Elements::add() takes type, name, lang and data. Files::add() stores an uploaded file or the file from a URL, and Files::save() accepts name, lang, description and transcription, the last two keyed by language. Invalid values and unknown element types throw an InvalidInputException.

Optional arguments

The user comes right after the required arguments. Pass the optional arguments after it by name, e.g. Pages::publish( $id, $user, at: '2030-01-01 00:00:00' ).

Argument
Methods
Effect
ref
Pages::add(), move(), copy()
ID of a sibling page; the page is inserted before it
parent
Pages::add(), move(), copy()
ID of the parent page; the page is added as its last sub-page
sections
Pages::add()
true moves content elements without a valid group into the first section of the page type
latestId
save(), Variants::revert()
ID of the version your changes are based on, see Concurrent changes
descendants
Pages::bulk(), Variants::bulk()
true also changes all sub-pages
at
publish(), publishMany()
Date and time to publish the latest version; it's published at once if empty
disk
Files::add(), relocate()
public (default) or private for files only delivered to visitors who can access their pages
preview
Files::add(), save()
Your own preview image; null generates previews automatically, false removes them in save()
upload
Files::save()
Replaces the stored file
translate
Variants::translate()
Callback that translates the texts, see Translate pages
fields
dropMany(), restoreMany(), purgeMany(), Variants::ignoreMany()
Columns to load in the returned items, all if empty

One or several items

  • publish( $id, ... ) and the other single-item methods return the changed model and throw a ModelNotFoundException if the item doesn't exist.
  • publishMany( $ids, ... ), dropMany() and the other Many methods return a collection of the changed items and skip unknown IDs. Up to 1,000 items can be changed at once, 100 for relocateMany().
  • bulk( $ids, $input, ... ) saves the same input to several items and returns a BulkResult with the saved ids, their new latest version IDs, the applied data and the number of failed items.

The Variants facade has the same methods for one language: publishMany(), ignoreMany(), dropMany(), restoreMany() and purgeMany() take the language after the page IDs, e.g. Variants::publishMany( $ids, 'de', $user ).

Act as one user

To avoid passing the same user to every call, use as() of any of the four facades. It returns an Acting object with the same methods as the facade, which adds the user to each call, so you leave out the user argument:

$pages = Pages::as( $request->user() );

$page = $pages->add( ['name' => 'About', 'path' => 'about'], parent: $rootId );
$page = $pages->publish( $page->id, at: '2030-01-01 00:00:00' );

Variants::as( $request->user() )->add( $page->id, 'de' );

Concurrent changes

Editors and your code may change the same item at the same time. Pass the latest_id of the version your changes are based on as latestId to save(). If someone saved a newer version in the meantime, the CMS merges both: values that only the other person changed are kept, and values changed by both get yours. Without latestId, the passed keys simply overwrite the latest draft.

This is useful for imports that run again and again: store $page->latest_id after each import and pass it the next time. Changes made by editors in the admin panel since then are kept, unless the import changes the same field.

Translate pages

Variants::translate() creates a missing language variant from the source language or merges the changes of the source language into a new draft of an existing variant. Pass a callback to translate the texts with your own service. It gets the list of texts, the target and source language and a short context with the website name and page title, and must return the translated texts in the same order:

use Aimeos\Cms\Facades\Variants;

Variants::translate( $page->id, 'de', $user, function( array $texts, string $to, ?string $from, string $context ) : array {
    return app( MyTranslator::class )->translate( $texts, $to, $from, $context );
} );

Without a callback, the texts are copied untranslated and the variant is marked as "Needs update". The AI package provides the translation used in the admin panel.

Permissions

Each method checks the permission of its action for the passed user, e.g. page:save for Pages::save(), and throws a PermissionException if the user lacks it. Calls without a user are refused too.

System calls

For changes made by your application itself, wrap the calls in Permission::system():

use Aimeos\Cms\Permission;

Permission::system( fn() => Pages::publish( $pageId ) );

Inside system(), calls without a user aren't checked and are recorded with system as editor. Users passed explicitly are still checked. Every call without a user inside the callback is trusted, including event listeners and synchronous jobs it triggers, so:

  • Keep the callbacks small and only wrap the CMS calls that need it.
  • Never pass $request->user() or Auth::user() inside system(), because guests would act as the system user.
  • Only pass fixed or validated values, e.g. a page ID from your own database instead of a value from a webhook payload.
  • Calls without a user aren't bound to a tenant, so initialize the tenant first, e.g. Tenancy::run( $tenantId, fn() => Permission::system( ... ) ).

system() only applies to the current process. Your own queued jobs must wrap their CMS calls in Permission::system() in handle(). Read operations decide about drafts by the logged-in user, so a job that reads drafts must call Auth::setUser() first.

Check permissions in your code

For your own operations, Permission::check( $action, $user ) throws the same exception and Permission::allowed( $action, $user ) returns the result. Permission::set( $user, $entries ) assigns roles and permissions without checking who calls it, so check that the current user may manage permissions before you use it in a controller.

The CMS permissions are also Laravel Gate abilities, so roles, deny entries and tenants apply to your own code:

$request->user()->can( 'page:publish' );
$this->authorize( 'page:save' );
Route::post( '/reports', ReportController::class )->middleware( 'can:page:view' );

See Authorization and Permissions for all roles and permissions.

Exceptions

All CMS exceptions extend Aimeos\Cms\Exception. Missing items throw Laravel's ModelNotFoundException.

Exception
Thrown if
Retry?
Aimeos\Cms\Exceptions\InvalidInputException
The input is invalid, unknown or exceeds the limits
No, fix the data
Aimeos\Cms\Exceptions\ConflictException
The stored data doesn't allow the operation, e.g. the language already exists or is the source language
No, the item is already in that state or must be changed first
Aimeos\Cms\Exceptions\PermissionException
The user lacks the permission
No, check the roles of the user
Illuminate\Database\Eloquent\ModelNotFoundException
The item doesn't exist or is in another tenant
No
Illuminate\Contracts\Cache\LockTimeoutException
Another process changed the page tree for longer than cms.lock seconds, e.g. a large move or copy
Yes, after a short delay

In a queued job, catch the exceptions you expect and let the queue retry the rest:

use Aimeos\Cms\Exceptions\ConflictException;
use Aimeos\Cms\Exceptions\InvalidInputException;

try {
    Variants::add( $pageId, 'de', $user );
} catch( ConflictException $e ) {
    // the page already has a German variant, nothing to do
} catch( InvalidInputException $e ) {
    report( $e ); // retrying won't help
    $this->fail( $e );
}

Set $tries and $backoff in the job, so a LockTimeoutException is retried a few seconds later.

Read content

Pages are read through the Aimeos\Cms\Models\PageView model, which combines the page tree with one language variant per page. Use live() to show pages to visitors. It picks the visible language, skips inactive pages and pages the visitor can't access, and loads the files and elements of the content:

use Aimeos\Cms\Models\PageView;

$page = PageView::live( $request->user(), 'de' )->whereKey( $pageId )->firstOrFail();

$page->title;    // published title
$page->lang;     // language of the variant, differs from 'de' if a fallback was used
$page->content;  // content elements with id, type, group and data
$page->files;    // files used in the content
$page->elements; // shared elements referenced in the content

Without a language, live() uses the current locale. If the page has no published and enabled variant in that language, live() returns the variant of a fallback language or the source language instead. The cms.translate.fallback setting only applies to menus, breadcrumbs and page lists, so return a 404 yourself if $page->lang is neither the requested language nor one you accept as fallback, e.g. de for de-CH.

The attributes contain the published content. latestValue( 'title' ) and latestAux( 'content' ) return the values of the latest draft instead, or the published ones if there's no newer draft; see Show drafts to editors. Pass true as second argument to use the draft only if the latest relation is already loaded, which avoids one query per page in lists.

Choose languages and pages

These query methods choose the language variant and the pages:

Method
Returns
language( ?string $lang, bool $trashed = false )
The variant in that language and skips pages without it; null returns the source language
fallback( string $lang, bool $trashed = false )
The variant in that language, its fallback languages (e.g. de-CH to de) or the source language
visible( string $lang )
The published and enabled variant in that language or its fallback languages, else the source variant; pages aren't skipped
localized( string $lang, bool $editor )
fallback() for editors, visible() for visitors
allVariants( bool $trashed = false )
Every variant, so a page is returned once per language
variant( string $id )
The variant with that ID
active()
Only enabled (1) and hidden (2) pages, inactive ones are skipped; combine it with the methods above

Pass true as $trashed to include deleted language variants, e.g. to list them for restoring. Of these methods, only live() checks the access rules of pages; see Check page access in your queries for your own queries.

Each language has its own path, e.g. about and ueber-uns. Look up pages by URL with allVariants()->where( 'path', $path ) and use the page ID or tag to get the same page in other languages. Pages are nested sets, so children, ancestors, descendants and the query methods of aimeos/laravel-nestedset are available too.

The Element and File models in Aimeos\Cms\Models work the same way: the attributes contain the published data, and latestValue() and latestAux() return the values of the latest draft.

Check page access in your queries

If you build your own queries for visitors instead of using live(), apply the access rules of the pages with the access() scope. It limits the query to the pages the user may access. Load the files and elements with contentRelations() if you render the content of the pages:

use Aimeos\Cms\Models\PageView;

$pages = PageView::visible( 'de' )
    ->active()
    ->access( $request->user() )
    ->with( PageView::contentRelations() )
    ->where( 'tag', 'news' )
    ->get();

To reject a single page with an error instead of skipping it, add the access flags with the withAccess() scope and pass the loaded page to PageAccess::check(). It throws an AuthenticationException for guests and aborts with 403 for users who aren't allowed:

use Aimeos\Cms\Models\PageAccess;

$page = PageView::visible( 'de' )->active()->withAccess( $request->user() )->whereKey( $pageId )->firstOrFail();
PageAccess::check( $page, $request->user() );

For a query builder without these scopes, PageAccess::apply( $query, $user ) and PageAccess::flags( $query, $user ) do the same.

Show drafts to editors

For a preview, Permission::previews() tells whether the user may see unpublished content. Load the page with localized() and its latest version for editors and with live() for everyone else. Draft content can use files and shared elements that aren't published yet, so editors get them from the latest version:

use Aimeos\Cms\Models\PageView;
use Aimeos\Cms\Permission;

$user = $request->user();
$lang = app()->getLocale();
$editor = Permission::previews( $user );

$query = $editor
    ? PageView::localized( $lang, true )->with( ['latest', ...PageView::contentRelations( 'latest.' )] )
    : PageView::live( $user, $lang );
$page = $query->whereKey( $pageId )->firstOrFail();

$title = $editor ? $page->latestValue( 'title' ) : $page->title;
$content = $editor ? $page->latestAux( 'content' ) : $page->content;
$files = $editor ? $page->latest?->files ?? $page->files : $page->files;
$elements = $editor ? $page->latest?->elements ?? $page->elements : $page->elements;

Editors also see inactive and restricted pages this way, because new pages are inactive until they are published. Visitors only get the published content of pages they may access. See Authorization and Permissions for who may preview drafts.

React to changes

The operations dispatch events from Aimeos\Cms\Events after the database transaction is committed, so rolled back changes are never announced. A change of one item dispatches the event of its action, e.g. Published, while a change of several items dispatches one Bulk event. Change::listen() calls your listener once per changed item for both:

use Aimeos\Cms\ContentType;
use Aimeos\Cms\Events\Change;

$stop = Change::listen( 'published', function( Change $change ) {
    if( $change->type() === ContentType::Page && $change->published ) {
        // $change->id, $change->versionId, $change->lang, $change->path, $change->editor, ...
    }
} );

$stop(); // removes the listener again

The actions are added, saved, moved, published, dropped, restored and purged, plus translated, source and ignored for page languages, or * for all of them. A Change has these public properties:

  • contentType: page, element or file as string; type() returns it as ContentType enum
  • action: the action from the list above
  • id and versionId: the changed item and its version
  • published: true if the version is public now, false if it's only scheduled or saved
  • lang, path and domain: the language and URL of pages
  • editor, tenant and source: who changed the item, in which tenant and through graphql, mcp or cli

Instead of a closure, you can pass the name of a class with a handle( Change $change ) method. If it implements ShouldQueue, the changed items of each event are handled in one queued job on the CMS queue, unless the class sets its own $connection or $queue:

use Aimeos\Cms\Events\Change;
use Illuminate\Contracts\Queue\ShouldQueue;

class NotifyCrm implements ShouldQueue
{
    public string $queue = 'crm';

    public function handle( Change $change ) : void
    {
        // called once per changed item in the queue worker
    }
}

Change::listen( ['published', 'dropped'], NotifyCrm::class );
Event
Dispatched when
Added
A page, element or file was created or a page was copied
Saved
A new draft was saved
Moved
A page was moved in the page tree
Published
The latest version was published or scheduled
Dropped, Restored, Purged
An item was moved to the trash, restored or deleted permanently
Bulk
Several items were changed by one call, e.g. bulk() or publishMany()
PageInvalidated
Rendered pages must be removed from caches
FilesRemoved
Stored files aren't public any more, e.g. to remove them from a CDN
PermissionChanged
The CMS permissions of a user were changed

The content events are only built if broadcasting is enabled or a listener is registered, so they cost nothing otherwise. See Webhooks to send changes to other systems without code.

Example: import articles

This queued job copies an article from another system of your application into a CMS page. It runs in the tenant of the article, uses the system permissions, keeps the changes of editors and publishes the page; read the note below the code if editors work on these pages too:

use Aimeos\Cms\Facades\Pages;
use Aimeos\Cms\Permission;
use Aimeos\Cms\Tenancy;
use App\Models\Article;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class ImportArticle implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;
    public int $backoff = 10;

    public function __construct( public int $articleId ) {}

    public function handle() : void
    {
        $article = Article::findOrFail( $this->articleId );
        $parentId = $article->category?->cms_page_id ?? throw new \RuntimeException( 'Category has no CMS page' );

        $input = [
            'name' => $article->title,
            'title' => $article->title,
            'content' => [
                ['type' => 'heading', 'data' => ['title' => $article->title, 'level' => '1']],
                ['type' => 'text', 'data' => ['text' => $article->body]],
            ],
        ];

        Tenancy::run( $article->tenant_id, fn() => Permission::system( function() use ( $article, $input, $parentId ) {
            if( $article->cms_page_id ) {
                $page = Pages::save( $article->cms_page_id, $input, latestId: $article->cms_version_id );
            } else {
                $page = Pages::add( $input, parent: $parentId );
            }

            Pages::publish( $page->id );
            $article->update( ['cms_page_id' => $page->id, 'cms_version_id' => $page->latest_id] );
        } ) );
    }
}

The page and version IDs are stored in your own table, so the job never uses IDs from outside. The path is generated from the title and the theme and page type are taken from the parent page. Without a parent, the page would be added at the top level, so the job fails if the category has no CMS page yet. Because the job passes latestId, a title corrected by an editor stays until the article title changes again.

publish() publishes the latest draft, which also contains unpublished changes an editor has made since the last import. If editors work on imported pages, leave out the publish() call and let them publish the pages after a review.

Change the behavior

The facades resolve the classes in Aimeos\Cms\Resource from the service container. Bind your own subclass in a service provider to change an operation everywhere, including the admin panel, GraphQL, MCP, AI and the commands:

$this->app->singleton( \Aimeos\Cms\Resource\Pages::class, \App\Cms\MyPages::class );

The classes in Aimeos\Cms\Resource\Support and methods marked @internal aren't part of the public API and may change in any release.

Testing

The CMS works with any database Laravel supports, so tests can use in-memory SQLite with RefreshDatabase or Orchestra Testbench. The factories of PageView, Element and File create items through the facades, so they get versions, search entries and events like content created by editors:

use Aimeos\Cms\Models\Element;
use Aimeos\Cms\Models\File;
use Aimeos\Cms\Models\PageView;
use Illuminate\Http\UploadedFile;

$root = PageView::factory()->published()->create( ['name' => 'Home', 'path' => ''] );
$page = PageView::factory()->for( $root, 'parent' )->published()->create( ['content' => [
    ['type' => 'text', 'data' => ['text' => 'Hello']],
]] );

PageView::factory()->count( 3 )->hidden()->create( ['parent_id' => $root->id] );
Element::factory()->published()->create( ['data' => ['type' => 'text', 'text' => 'Shared']] );
File::factory()->private()->create( ['file' => UploadedFile::fake()->createWithContent( 'doc.pdf', '%PDF-1.4' )] );

Without published(), only a draft is created. hidden() hides pages in the navigation and inactive() disables them. Files are fake 100x100 PNG images unless you pass a file or URL.

Add the HasCmsPermissions traits to the user model and its factory to create editors:

class User extends Authenticatable
{
    use \Aimeos\Cms\Concerns\HasCmsPermissions;
}

class UserFactory extends Factory
{
    use \Aimeos\Cms\Database\Factories\HasCmsPermissions;
}

// in a test
$editor = User::factory()->cms( 'editor', '!page:drop' )->create();

$this->actingAs( $editor )->post( '/reports' )->assertOk();
$this->assertTrue( $editor->can( 'page:save' ) );

The facades support shouldReceive() and spy() like all Laravel facades. The admin panel, GraphQL, MCP and AI use the facades too, so a mock also replaces the operations they call:

Pages::shouldReceive( 'publish' )->once()->with( 'page-id', $user )->andReturn( $page );

To test events, use Event::fake() or collect the Change objects in a Change::listen() listener. $this->artisan( 'cms:demo' ) creates a complete tree of published demo pages.