在控制器方法的模型类型提示路由参数中预处理主键

Preprocessing primary keys in a controller method's model type hinted route parameter

我有一些模型,其中我使用自定义非顺序唯一 ID,类似于标准 UUID。它们有 64 位长,我应该可以使用 8000 多年,所以我将它们存储为无符号大整数。

然而,作为 base10 数字,它们在 19 位时有点长且笨拙。为了解决这个问题,我可以将它们转换为 base36 数字(包含 0-9 和 a-z 的字符串)。它们最多为 15 个字符,但在接下来的 30 年左右应该只有 11 或 12 个字符。

我的问题是是否有一种方法可以挂接到 Laravel 的类型提示依赖注入,以便像这样的构造函数方法:

public function show(ModelName $modelName) {
    dump($modelName);
}

使用标准资源路由:

Route::get('modelName/{modelName}', 'ModelController@show');

将 return 使用 base36 字符串调用时的正确模型

如果我没理解错的话,路由绑定可以解决你的问题:

在你的RouteServiceProvider的启动函数中:

public function boot()
{
    Route::bind('modelName', function ($value) {
        return ModelName::where('name', $value)->firstOrFail();
    });

    // ...
}

或者,如果您想在模型级别(可能有特征)解决它,您可以覆盖模型中的 resolveRouteBinding 函数:

public function resolveRouteBinding($value, $field = null)
{
    return $this->where('name', $value)->firstOrFail();
}

来源:https://laravel.com/docs/8.x/routing#customizing-the-resolution-logic