Skip to content

Handle enum instance when throwing errors involving query parameters #55977

@jtheuerkauf

Description

@jtheuerkauf

Laravel Version

11.45+

PHP Version

8.3.22+

Database Driver & Version

No response

Description

Using an enum as an "ID" when using find() and its derivatives is supported because the where logic converts the instance via enum_value().

In Builder::findOrFail() the $id variable is passed to ModelNotFoundException::setModel() where it becomes part of the exception message. But nothing makes sure the value of the ID can be used in a string.

In 11.x up to 12.18 the line looks like:

if (is_null($result)) {
    throw (new ModelNotFoundException)->setModel(
        get_class($this->model), $id
    );
}

In setModel() method:

if (count($this->ids) > 0) {
    $this->message .= ' '.implode(', ', $this->ids);
}

I notice the same behavior would occur if the count of fetched Models doesn't match the ID count.

Steps To Reproduce

  1. create table foo(id int) (no data)
  2. artisan make:model Foo
  3. Make new class enum FooNum: int { case One = 1; }
  4. Query Foo::findOrFail(FooNum::One)

Expected error (approximately):
No query results for model [Foo] 1

Got instead (approximately):
PHP Fatal error: Uncaught Error: Object of class FooNum could not be converted to string

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions