Skip to content

Model Discovery ​

Model discovery automatically maps Eloquent models to OData entity types. Call $this->discoverModel() in your service's configure() method, and the library inspects the model's database table, column types, casts, and relationships.

The declaration rule changed in 4.0

A discovered model is described by its table and its class. What goes beyond the table is declared on the model's class; what depends on the runtime comes from a resolver bound in the container. Every declaration adds to what discovery finds; none overrides it. And the wire carries exactly what $metadata declares.

So there are two surfaces and nothing in between: a discovered model, or a custom entity set. To rename a column, give it another type or serve a cut of the table, write a custom entity set.

Basic usage ​

php
protected function configure(EdmBuilderInterface $builder): EdmBuilderInterface
{
    $this->discoverModel(Flight::class);
    $this->discoverModel(Passenger::class);

    return $builder->namespace($this->namespace());
}
// No registerBindings() needed -- discovered models are auto-bound.

Each discoverModel() call:

  1. Inspects the model's table via Schema::getColumns()
  2. Maps each column to an OData primitive type
  3. Uses $model->getKeyName() as the entity type key
  4. Discovers Eloquent relationships and maps them to navigation properties
  5. Creates an entity set with a pluralized name
  6. Auto-registers an EloquentBinding in the ResolverMap

Naming conventions ​

ElementConventionExample
Entity type nameModel short class nameFlight
Entity set namePluralized type nameFlights
Property nameColumn name (snake_case)flight_id

The set name is the English plural of the type name: Person becomes People. Name either with #[ODataEntity]. Two models that resolve to the same entity type or entity set name — two Item classes in different namespaces, say — fail loud while the schema is built, with a message naming both classes. changed in 4.0The service used to answer every request with a 500 about a missing resolver instead.

Column type mapping ​

The library maps database column types to OData primitive types. When a model declares a cast for a column, the cast type takes precedence over the database type.

Database type mapping ​

DB TypeOData Type
string, varchar, char, textEdm.String
integer, int, tinyint, smallint, mediumintEdm.Int32
bigintEdm.Int64
float, double, realEdm.Double
decimal, numericEdm.Decimal
boolean, boolEdm.Boolean
dateEdm.Date
datetime, timestampEdm.DateTimeOffset
timeEdm.TimeOfDay
blob, binaryEdm.Binary
json, jsonbEdm.String
uuid, guidEdm.Guid
Unknown typesEdm.String (fallback)

Cast type overrides ​

Eloquent CastOData Type
'integer', 'int'Edm.Int32
'float', 'double'Edm.Double
'decimal'Edm.Decimal
'boolean', 'bool'Edm.Boolean
'date'Edm.Date
'datetime', 'timestamp'Edm.DateTimeOffset
'immutable_date'Edm.Date
'immutable_datetime'Edm.DateTimeOffset
'string'Edm.String
'array', 'json', 'collection', 'object'Edm.String

A structured cast goes out as the string $metadata declares: its JSON text, which the client parses. OData has no JSON type. changed in 4.0The decoded value used to go out as a JSON object, against the declared Edm.String.

Cast format suffixes (e.g., 'datetime:Y-m-d H:i:s') are stripped before mapping. A cast the table does not list — an enum cast, or a custom cast class — is ignored, and the column falls back to its database type.

Both declaration idioms are read: the legacy protected $casts property and the protected function casts(): array method Laravel has scaffolded since 11.x. (Before 3.0.5 only the property was — discovery instantiated models without their constructor, which is where Eloquent merges casts() in, so a modern model was read as if it had no casts at all. The symptom to recognise, if you are on an older version: $table->boolean() surfacing as Edm.Int32, because both SQLite and MySQL store a boolean as tinyint(1).)

Enum casts are not projected as Edm.EnumType

An int-backed PHP enum cast on a discovered model does not become an Edm.EnumType: the column is typed from the database (an integer column stays Edm.Int32) and the wire value stays the backing integer.

The symbolic projection — enum members in $metadata, member names in responses — is available on custom entity sets, where columns() accepts an enum class-string. Use one when the enum semantics matter to the client, or keep the backing integer and let the client map the values.

Type facets ​

Discovery also reads the facets of each column from the table schema and publishes them in $metadata. A client can then format and validate a value without a second declaration. UI5's sap.ui.model.odata.type.Decimal, for example, formats by Scale.

ColumnFacets in $metadata
NOT NULLNullable="false"
decimal(p,s), numeric(p,s)Precision="p" Scale="s"
decimal(p)Precision="p" Scale="0"
varchar(n), char(n), nvarchar(n), character varying(n)MaxLength="n"
nvarchar(max)MaxLength="max"

A decimal(19,6) column therefore appears as:

xml
<Property Name="amount" Type="Edm.Decimal" Nullable="false" Precision="19" Scale="6"/>

Rules:

  • A key is never nullable. SQLite reports an integer primary key as nullable, and discovery ignores that report.
  • A facet needs a type that can carry it. MaxLength goes only on Edm.String and Precision/Scale only on Edm.Decimal. If a cast changes the type, the column's length or scale is not carried over.
  • A nullable column with nothing else to say gets no facets. Its Property element carries only name and type, and the spec default (Nullable="true") applies.
  • A facet resolver can override the column, see below.
  • The facets survive odata:cache. The cached schema announces the same facets as the one built on each request.

The facets come from the column type as the database reports it. SQLite keeps the declared type text, but Laravel's SQLite grammar writes decimal() as numeric and string() as varchar, both without arguments. A SQLite database created by migrations therefore yields Nullable but no Precision, Scale or MaxLength. MySQL, MariaDB, PostgreSQL and SQL Server report all of them.

Overriding facets ​

Some facets are not a fact of the column. A unit price stored as decimal(19,6) may have to be announced with four decimals, because UI5 formats and validates input by Scale. Say so with a resolver: bind your own implementation of ColumnFacetResolverInterface. Discovery calls it for every column with the model class, the column name, the model's cast for that column and the facets taken from the schema, and uses the facets it returns:

php
use LaravelUi5\OData\Edm\Type\TypeFacets;
use LaravelUi5\OData\Service\Contracts\ColumnFacetResolverInterface;

final class PriceDecimals implements ColumnFacetResolverInterface
{
    public function resolve(string $modelClass, string $column, ?string $cast, TypeFacets $facets): TypeFacets
    {
        return $cast === UnitPrice::class
            ? $facets->withScale(config('shop.price_decimals'))
            : $facets;
    }
}

// in a service provider
$this->app->bind(ColumnFacetResolverInterface::class, PriceDecimals::class);

The resolver receives the model class, so it can answer for one model as well as for a cast across all of them ($modelClass === Product::class && $column === 'unit_price'). The default resolver returns the facets unchanged. There is one binding, not a chain: a new binding replaces the previous one. To keep another resolver's answer, decorate that resolver.

The order per column is: schema → resolver. changed in 4.0A third layer, #[ODataProperty(nullable:, precision:, scale:)] on a hooked property, is removed. A key stays non-nullable whatever the layers say. Discovery refuses facets the type cannot carry and throws a LogicException while building the schema:

  • Scale on anything but Edm.Decimal;
  • Precision on anything but Edm.Decimal or a temporal type;
  • MaxLength on anything but Edm.String or Edm.Binary;
  • a Scale above the Precision.

The resolver runs when the schema is built

A cold service builds its schema on every request, so it sees the current value. A service cached with odata:cache keeps the value the resolver returned when the cache was written. When the fact behind it changes, run odata:cache again.

UI5's V4 types treat Nullable="false" and MaxLength as constraints. A control bound two-way to such a property validates input against them.

(Before 3.1.0 discovery emitted no facets at all: every decimal was a bare Edm.Decimal.)

Relationship discovery ​

The library discovers relationships by instantiating the model and calling its public methods. Methods that return an Eloquent Relation are mapped to navigation properties.

Eloquent RelationOData NavigationisCollection
HasManyCollectionyes
BelongsToSingle-valuedno
HasOneSingle-valuedno
BelongsToManyCollectionyes

Skipped relationships (not mapped):

  • MorphMany, MorphOne, MorphTo, MorphToMany (polymorphic)
  • HasManyThrough, HasOneThrough (through-relationships)

Why polymorphic relations stay out

All of them, also those with a fixed target (morphMany, morphOne, morphToMany, morphedByMany). A polymorphic join runs over a type column plus an id (commentable_type, commentable_id). A navigation property in $metadata can state its join only as pairs of properties, so it cannot express the type condition. The schema would describe half a relation, and with morphTo the target type itself changes from row to row. Ambiguity at the level of the contract works against what OData is for.

To serve such an edge, model it explicitly:

  • a custom entity set that selects the rows for one type, e.g. Comments filtered on commentable_type = Post::class;
  • a virtual expand that attaches them to the parent as a navigation of your own;
  • or a regular hasMany / belongsTo on a table that is not polymorphic.

Each of these puts into the schema exactly what the service does.

A navigation property takes the name of its method. A relation the model never serializes (see What the model never serializes) is not discovered.

Navigation properties are only wired when both sides of the relationship are discovered. If you discover Flight but not Passenger, the passengers navigation property is not created.

Navigation property bindings on entity sets are automatically created for each discovered navigation property.

What the model never serializes changed in 4.0 ​

Discovery declares exactly the columns and relations the model's toArray() carries. A non-empty $visible admits only what it names, and $hidden removes from that, as Eloquent does:

php
class Account extends Model
{
    protected $hidden = ['password', 'tokens'];   // a column and a relation
}

password and tokens are neither declared in $metadata nor on the wire, and a $select, $filter or $orderby naming them answers 400. Before 4.0 this needed #[ODataEntity(useHidden: true)], and $visible was ignored: a column could be declared, filterable, and never delivered.

The key must stay serializable. A key in $hidden, or outside a non-empty $visible, fails loud while the schema is built: an entity whose key never reaches the client cannot be read.

$hidden shapes the contract, not who may read a row. Row-level access belongs to the read gate or to the query of a custom entity set.

The wire carries the declared properties changed in 4.0 ​

A row of a discovered set — top level, single entity, or expanded at any depth — carries its entity type's declared properties, the expanded navigations with their @odata.count, and the $compute aliases. Nothing else that toArray() holds goes out: not a model's $appends, not the pivot of a belongsToMany row, not a relation loaded through $with and left unexpanded. A value the client should see is declared — as a column, as a computed property, or in a custom entity set.

Class attributes ​

Three PHP attributes on the model's class add to what discovery finds. They are configuration read by discovery, not OData vocabulary terms. None sits on a PHP property: a declared property named like a column shadows Eloquent's attribute bag. changed in 4.0#[ODataProperty], #[ODataIgnore] and #[ODataNavigation], which needed such a property, are removed; see Upgrading from 3.x.

#[ODataEntity]: the names ​

php
use LaravelUi5\OData\Service\Discovery\Attributes\ODataEntity;

#[ODataEntity(name: 'Airplane', entitySet: 'Airplanes')]
class Flight extends Model
{
    // Entity type will be "Airplane" instead of "Flight"
    // Entity set will be "Airplanes" instead of "Flights"
}

Both arguments are optional. changed in 4.0useHidden: is gone; $hidden always applies.

#[ODataAnnotate]: vocabulary on a column since 4.0 ​

Annotates one property, named by the attribute, with any number of vocabulary terms:

php
use LaravelUi5\OData\Service\Discovery\Attributes\ODataAnnotate;

#[ODataAnnotate('price', new ISOCurrency(new Path('currency')))]
#[ODataAnnotate('name', new Label('Product name'), new Description('Shown in lists'))]
class Product extends Model {}

The property must be one the entity type declares, or discovery fails loud. Details, and the resolver that annotates columns across models, are on Applying annotations.

#[ODataComputed]: a property with no column since 4.0 ​

Some values belong in the row but have no column: the code beside a code-list key (unit beside unit_id), or the tenant's base currency next to an amount. UI5's Unit and Currency types need them in the row. Declare such a property on the class, with its type and facets:

php
use LaravelUi5\OData\Edm\EdmPrimitiveType;
use LaravelUi5\OData\Service\Discovery\Attributes\ODataComputed;

#[ODataComputed('currency', EdmPrimitiveType::String, nullable: false, maxLength: 3)]
#[ODataComputed('unit', EdmPrimitiveType::String, maxLength: 3)]
#[ODataAnnotate('price', new ISOCurrency(new Path('currency')))]
#[ODataAnnotate('quantity', new Unit(new Path('unit')))]
class ServiceItem extends Model {}

Its value is an SQL expression, answered by the bound ColumnExpressionResolverInterface (see A property that is an expression) for the model class and the property name:

php
final class ServiceItemExpressions implements ColumnExpressionResolverInterface
{
    public function __construct(private readonly string $baseCurrency) {}

    public function expression(string $source, string $property): ?string
    {
        if ($source !== ServiceItem::class) {
            return null;
        }

        return match ($property) {
            'currency' => "'" . $this->baseCurrency . "'",
            'unit'     => '(select code from units where units.id = service_items.unit_id)',
            default    => null,
        };
    }
}

The engine selects (<expression>) AS <name> on every read of the model — a list, a single entity, an expanded row, a nested $select — and $filter, $orderby, $search and $compute use the same expression. $metadata marks the property Core.Computed. A literal per request, such as a tenant's base currency, is simply the resolver's answer for that request.

Rules:

  • The name must not be a column, and the model must serialize it (not in $hidden, inside a non-empty $visible). Discovery fails loud otherwise.
  • A computed property no resolver answers fails when it is queried, with a message naming the property and the model.
  • The declaration is static, so odata:cache keeps it. The expression is asked for on every request.

What is NOT discovered ​

  • Eloquent accessors and $appends — no column, so no property. Declare a computed property instead.
  • What the model never serializes — see above.
  • Guarded/fillable — irrelevant for a read-only service.

Upgrading from 3.x ​

3.x4.0
#[ODataEntity(useHidden: true)]drop the argument; $hidden always applies
#[ODataIgnore] on a column or relationput it in the model's $hidden
#[ODataProperty(nullable:, precision:, scale:)]a ColumnFacetResolverInterface that answers for the model and column
#[ODataProperty(type:)]a cast
#[ODataProperty(name:)], #[ODataNavigation(name:)]a custom entity set (both renames never reached the wire)
a vocabulary attribute on a hooked property#[ODataAnnotate] on the class; the hooked property can go
a client reading $appends or pivot from a rowdeclare the value, or serve a custom entity set

The full list of what 4.0 changes is in the package's CHANGELOG.

Coexistence with manual schema ​

You can mix discovered models with manually declared types in the same service:

php
protected function configure(EdmBuilderInterface $builder): EdmBuilderInterface
{
    // Auto-discover these models
    $this->discoverModel(Flight::class);
    $this->discoverModel(Passenger::class);

    // Manually declare a function
    $countFunc = new EdmFunction(name: 'GetFlightCount', returnType: $int32);
    $countImport = new FunctionImport('GetFlightCount', $countFunc);

    return $builder
        ->namespace($this->namespace())
        ->addFunction($countFunc)
        ->addFunctionImport($countImport);
}

protected function bindFunctions(RuntimeSchemaBuilderInterface $builder): void
{
    // Discovered models are auto-bound -- only bind the function:
    $container = $builder->getEdmx()->getEntityContainer();
    $builder->bindFunctionImport(
        $container->getFunctionImport('GetFlightCount'),
        new class implements FunctionResolverInterface {
            public function resolve(QueryPlanInterface $plan): mixed
            {
                return Flight::count();
            }
        },
    );
}

If you register a binding for a discovered model in registerBindings(), the manual binding overrides the auto-registered one.