Models

Creating models

A model represents a content type of your Prismic environment. Each model should extends the abstract base model from the package.

For example; We have a content type called 'page':

namespace App;

use RobinDrost\PrismicEloquent\Model;

class Page extends Model {}

This base setup is already enough to query the api for your documents.

You can overwrite the static method getTypeName to specify the content type. Prismic Eloquent will use the name of the class by default and convert camelCase to snake_case.

Alter fields

Your model can implement methods that are called when a field is called. For example a 'title' field can be changed like:

namespace App;

use RobinDrost\PrismicEloquent\Model;

class Page extends Model 
{
    public function getTitleField($value)
    {
        return $value . ' suffix for my title';
    }
}

You model will now use getTitleField when $page->title is called.

Local scopes

Local scopes like used in the normal Eloquent models are also available.

namespace App;

use RobinDrost\PrismicEloquent\Model;

class Page extends Model 
{
    public function scopeTestTitle($query)
    {
        $query->where('title, 'test');
    }
    
    public function scopeFilterByRequest($query, Request $request, $field)
    {
        if ($request->filled($field)) {
            $query->where($field, $request->get($field);
        }
    }
}

Page::testTitle()->first();
Page::filterByRequest($request, 'field_name')->first();

Camel case fields

You can access your model field by camelCase. Prismic Eloquent will automatically change camel case to snake case since this is the default in Prismic.

For example:

$page->myAwesomeTitle

// actual field name in Prismic
// my_awesome_title

You can disable this behaviour by overwriting the fieldsToSnakeCase property on your model.

Last updated