Skip to content

[12.x] Adds resolver for specific Model route binding fields #55646

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: 12.x
Choose a base branch
from

Conversation

DarkGhostHunter
Copy link
Contributor

What?

This PR allows the developer to transform incoming route binding fields values, instead of overriding the Route Binding methods. The main problematic that it solves modifying the field value or query.

The developer can use resolveField() on the target model to register a callback that will be executed for the specific implicit binding field. The callback receives the value, field name, and query builder. The developer may return a new field value, or completely hijack the query for better control.

In the following example, the Car model doesn't have an ulid column. Instead of creating that column in the database, we can resolve the ulid field and transform the query to find the record by its UUID:

use Illuminate\Database\Eloquent\Model;
use Symfony\Component\Uid\Ulid;

class Car extends Model 
{
    public static function booted()
    {
        static::resolveField('ulid', function ($value, $field, $query) {
            return $query->where('id', Ulid::fromString($value)->toRfc4122())
        })
    }
}

When the callback doesn't return an Eloquent Query or Base Query, it will use the returned value as part of the where key:

Car::resolveField('id', function ($value) {
    return Str::of($value)->snake()->lower()->toString();
});

Also, because the field resolver is a callable, the user can register invokable class instances as resolver if needed, especially if their logic is too much for a single function.

Car::resolveField('uuid', new UuidResolver())

Finally, the resolver can be deleted by setting null.

Car::resolveField('uuid', null);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants