Models
The widgets read and save plain Eloquent models. Relations are methods, JSON attributes are casts, and a few small contracts from octoberrain/contracts add trees, manual sorting and file uploads. Every model in the demo app is a stock Eloquent model: the posts, categories, tags and groups of the Showcase, Laravel's User model as the authors, and the Sample record the Reference pages edit.
Relations
Declare relations as methods, the usual Laravel way. The post belongs to a category and an author, has tags, comments and a featured image:
/**
* category is the category the post is filed in.
*/
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
/**
* author is the user who wrote the post.
*/
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id');
}
/**
* tags label the post, picked or created by the tag list.
*/
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class, 'post_tag');
}
/**
* comments are the reader comments, counted by the comments list column.
*/
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
/**
* featured_image is the image uploaded for the post, a file record named by its field.
*/
public function featured_image(): MorphOne
{
return $this->morphOne(File::class, 'attachment')->withAttributes(['field' => 'featured_image']);
}The author belongs to a primary group and to other groups:
/**
* The primary group this user belongs to (belongs-to relation, rendered by
* the "Primary Group" relation field on the form).
*/
public function primary_group(): BelongsTo
{
return $this->belongsTo(UserGroup::class, 'primary_group_id');
}
/**
* The secondary groups this user belongs to (many-to-many relation,
* rendered by the "Secondary Groups" relation field on the form).
*/
public function groups(): BelongsToMany
{
return $this->belongsToMany(UserGroup::class, 'user_user_group');
}A relation field, column or scope finds its relation by name, so a field named category reads the category() method. The widgets call a method that takes no arguments to see whether it returns a relation, so keep relation methods free of required parameters.
How the widgets read a model
The widgets never ask a model about its relations directly. They go through the model inspector service, app('model.inspector'), which reads your relation methods and casts. It answers the questions the widgets need:
| Method | Returns |
|---|---|
| hasRelation($model, $name) | whether the model has a relation by that name. |
| getRelationType($model, $name) | the relation type, such as belongsTo or belongsToMany. |
| isRelationTypeSingular($model, $name) | whether the relation holds one record, such as belongsTo or hasOne. |
| makeRelation($model, $name) | an instance of the related model. |
| getRelationSimpleValue($model, $name) | the related key, or the list of related keys. |
| setRelationValue($model, $name, $value) | sets a relation from a key or keys. A belongsTo is associated, and other relations hold the related records in memory. |
| isJsonable($model, $attribute) | whether the attribute stores JSON, through an array, json, object or collection cast. |
Your own extensions can ask the same questions, for example app('model.inspector')->getRelationType($user, 'groups') returns belongsToMany.
Saving relations
A relation field posts its value under the relation's name: a key for a belongsTo, a list of keys for a belongsToMany. Eloquent does not take relation names as attributes, so your save code maps them: a belongsTo posts onto its foreign key, and a belongsToMany syncs once the record exists. The Authors form saves the user's groups this way:
// The belongs-to field posts under its relation name, so it maps onto the foreign key
if (array_key_exists('primary_group', $data)) {
$data['primary_group_id'] = $data['primary_group'] ?: null;
}
// The many-to-many ids sync once the record exists, and an empty selection clears them
$hasOtherGroups = array_key_exists('groups', $data);
$otherGroups = ($data['groups'] ?? null) ?: [];
unset($data['groups'], $data['primary_group'], $data['password_confirmation']);
$user->fill($data)->save();
if ($hasOtherGroups) {
$user->groups()->sync($otherGroups);
}The same goes for a tag list bound to a relation, which posts the keys of the picked tags and creates the new ones first. The Reference pages save every relation of the sample with one loop, which asks the model inspector which values are relations:
/**
* saveExample fills the record from the posted values and saves it, where a belongs-to field maps onto its foreign key and a belongs-to-many field syncs once the record exists.
*
* @param array<string, mixed> $data
*/
protected function saveExample(Model $model, array $data): void
{
$relatedIds = [];
foreach ($data as $name => $value) {
// Widgets that store their own values, such as file uploads and repeaters bound to a relation, post no value
if ($value === FormField::NO_SAVE_DATA) {
unset($data[$name]);
continue;
}
if (!app('model.inspector')->hasRelation($model, $name)) {
continue;
}
$relation = $model->{$name}();
if ($relation instanceof BelongsTo) {
$relation->associate($value ?: null);
}
elseif ($relation instanceof BelongsToMany) {
$relatedIds[$name] = $value ?: [];
}
unset($data[$name]);
}
$model->fill($data)->save();
foreach ($relatedIds as $name => $ids) {
$model->{$name}()->sync($ids);
}
}Some widgets save their relation themselves and post no value: a file upload, a repeater and a nested form bound to a relation.
When a field that another field dependsOn changes, the form refreshes from the posted values, and it sets a posted relation on the model through setRelationValue() for the refresh. That is how the post's permalink follows a newly picked category before the post is saved, see extending the form.
Validation
A model has no rules of its own, so validate the values in the controller before saving them:
- read the values with
getSaveData(); - run Laravel's
Validator::make()on them, with rules that can depend on the record, such as a unique email that ignores the record being edited; - when it fails,
validate()throws aValidationException, which returns its messages by field name and marks those fields as invalid.
The Authors and post forms do exactly this, see validation in the controller. The form cannot read the rules from your controller, so mark required fields with required: true in the YAML when you want the marker.
JSON attributes
Fields that save structured values, such as a repeater, a nested form or a tag list in array mode, need an attribute that stores JSON. Give it an array cast, as the post does for its keywords:
/**
* casts returns the attributes that should be cast, where the array cast stores the keywords tag list as JSON.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'keywords' => 'array',
'published' => 'boolean',
'published_at' => 'datetime',
'review_on' => 'date',
'views' => 'integer',
];
}The user's links attribute has one too:
/**
* The attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'links' => 'array',
'is_mail_blocked' => 'boolean',
'is_two_factor_enabled' => 'boolean',
];
}The widgets read any array, json, object or collection cast as JSON, through the model inspector's isJsonable().
File attachments
File uploads store each file as a record of a file model, related to the record it belongs to. The file model is a plain Eloquent model that implements October\Contracts\Database\AttachmentInterface:
fromPost($fileInput)stores an uploaded file and fills in the model;getPath()returns the address of the file, andgetThumb($width, $height, $options)the address of a thumbnail;- the static
getMaxFilesize()returns the largest file it accepts, in kilobytes.
The upload field also reads the file_name, file_size, title and description attributes of each file. The demo's file model stores the uploads on the public disk, under uploads/public, or under uploads/protected when the file is private. It has no image resizer, so its thumbnail is the image itself:
/**
* fromPost stores an uploaded file, in the protected folder when the relation made the file private.
*/
public function fromPost($fileInput): static
{
return $this->fromFile($fileInput->getRealPath(), $fileInput->getClientOriginalName());
}
/**
* fromFile stores a local file under a unique disk name and fills in its name, size and type.
*/
public function fromFile(string $path, ?string $fileName = null): static
{
$file = new LocalFile($path);
$this->file_name = $fileName ?? $file->getFilename();
$this->file_size = $file->getSize();
$this->content_type = $file->getMimeType() ?? 'application/octet-stream';
$this->disk_name = Str::random(40).'.'.strtolower(pathinfo($this->file_name, PATHINFO_EXTENSION));
$this->is_public ??= true;
$this->getStorageDisk()->putFileAs($this->getStorageFolder(), $file, $this->disk_name);
return $this;
}
/**
* getPath returns the public address of the file, or of another file in its folder.
*/
public function getPath($fileName = null): string
{
return $this->getStorageDisk()->url($this->getStorageFolder().'/'.($fileName ?? $this->disk_name));
}
/**
* getThumb returns the address of the file itself, since the demo has no image resizer to make a thumbnail.
*/
public function getThumb($width, $height, $options = []): string
{
return $this->getPath();
}
/**
* getMaxFilesize returns the largest upload PHP accepts, in kilobytes.
*/
public static function getMaxFilesize(): float
{
return UploadedFile::getMaxFilesize() / 1024;
}When the file model also implements SortableInterface, dragging files into a new order stores it through setSortableOrder(), and a getSortOrderColumn() method names the column the field lists the files by.
The record holds its files through a hasOne or morphOne relation for one file, and a hasMany or morphMany relation for a list. The demo's relations are morph relations, each narrowed to its own field with withAttributes(), which both filters the files and sets the field on a new one, like the post's featured image in its relations. A relation can set other attributes the same way, such as the private contract on the file upload page.
An upload is held until the record saves. The field stores the file with no record to belong to and keeps its key in the session, against the form's session key, and a removal is held the same way. When the record's Eloquent saved event fires, the field attaches the held uploads and deletes the files held for removal, so saving the record is all it takes. Leaving the page without saving leaves the record as it was, and the held uploads stay in the table with no record. With deferredBinding: false, an upload to a saved record is attached straight away.
The files live in a files table, whose attachment_id column is nullable, since a held upload belongs to no record yet:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations, creating the files table the file upload fields store their uploads in.
*
* Each file names the record it belongs to through attachment_type and attachment_id, and the
* relation it fills through field, while an upload waiting for its record to save has no
* attachment_id yet.
*/
public function up(): void
{
Schema::create('files', function (Blueprint $table) {
$table->increments('id');
$table->string('disk_name');
$table->string('file_name');
$table->integer('file_size');
$table->string('content_type');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('field')->nullable();
$table->integer('attachment_id')->nullable();
$table->string('attachment_type')->nullable();
$table->boolean('is_public')->default(true);
$table->integer('sort_order')->nullable();
$table->timestamps();
$table->index(['attachment_type', 'attachment_id', 'field'], 'files_master_index');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('files');
}
};Trees
A tree model implements October\Contracts\Database\TreeInterface, which the list structure, the relation field and the record finder read:
getChildren()returns the records directly below a record, andgetChildCount()how many records sit below it;- the
getNested()scope runs the query and returns its top level records, with their children nested below them; - the
listsNested()scope returns the values of a column in tree order, indented by depth.
The post category stores a simple tree, where each category names its parent in a parent_id column:
/**
* Category is a post category stored as a simple tree, where each category points at its parent and keeps its place among its siblings in a sort order column.
*/
#[Fillable(['name', 'slug', 'description', 'parent_id'])]
class Category extends Model implements SortableInterface, TreeInterface
{
/** @use HasFactory<CategoryFactory> */
use HasFactory;
/**
* parent is the category this one sits below, or null at the top level.
*/
public function parent(): BelongsTo
{
return $this->belongsTo(Category::class, 'parent_id');
}
/**
* children are the categories directly below this one, in their sort order.
*/
public function children(): HasMany
{
return $this->hasMany(Category::class, 'parent_id')->orderBy('sort_order');
}
/**
* getChildren returns the categories directly below this one, nested in memory by getNested.
*/
public function getChildren(): Collection
{
return $this->children;
}
/**
* getChildCount returns the number of categories anywhere below this one.
*/
public function getChildCount(): int
{
return $this->getAllChildren()->count();
}
/**
* scopeGetNested returns the top level categories of the query with their children nested below them, leaving out categories whose parent the query skipped.
*/
public function scopeGetNested($query): Collection
{
$categories = $query->orderBy('sort_order')->get()->keyBy('id');
foreach ($categories as $category) {
$category->setRelation('children', $category->newCollection());
}
$roots = $this->newCollection();
foreach ($categories as $category) {
if (!$category->parent_id) {
$roots->push($category);
}
elseif ($parent = $categories->get($category->parent_id)) {
$parent->children->push($category);
}
}
return $roots;
}
/**
* scopeListsNested returns the column values keyed by the key column, in tree order and indented by depth.
*
* @return array<int|string, string>
*/
public function scopeListsNested($query, $column, $key = null, $indent = ' '): array
{
$result = [];
$addCategories = function (Collection $categories, int $depth) use (&$addCategories, &$result, $column, $key, $indent) {
foreach ($categories as $category) {
$label = str_repeat($indent, $depth).$category->{$column};
if ($key === null) {
$result[] = $label;
}
else {
$result[$category->{$key}] = $label;
}
$addCategories($category->getChildren(), $depth + 1);
}
};
$addCategories($query->getNested(), 0);
return $result;
}Dragging a row in a list structure saves the move in two steps: the list associates the model's parent relation with the new parent, and when the model implements SortableInterface it passes setSortableOrder() the keys of the rows in their new order. The category stores that order in sort_order:
/**
* setSortableOrder stores a new order for the given categories, numbered from one unless the orders are supplied.
*
* @param array<int, int|string> $itemIds
* @param array<int, int>|bool|null $itemOrders
*/
public function setSortableOrder($itemIds, $itemOrders = null): void
{
if (!is_array($itemIds)) {
return;
}
$itemIds = array_values($itemIds);
$orders = is_array($itemOrders) && count($itemOrders) === count($itemIds)
? array_values($itemOrders)
: range(1, count($itemIds));
foreach ($itemIds as $index => $id) {
static::query()->whereKey($id)->update(['sort_order' => $orders[$index]]);
}
}Reorderable lists
A flat reorderable list works on any model. To store the new order, the model implements October\Contracts\Database\SortableInterface with a setSortableOrder() method and a sort_order column, as the User model does. See reorderable list.
Next steps
- Building a Form Page: saving and validating a form
- Relation: relation fields and the trees they show
- Widgets and Controllers: how the widgets' handlers reach your controller