Php 带有非基元类型暗示参数的Laravel API端点

Php 带有非基元类型暗示参数的Laravel API端点,php,laravel,uuid,Php,Laravel,Uuid,我有一个API端点,我想将UUID传递给它。我正在使用一个名为UUID的包将UUID集成到我的应用程序中。我希望采用UUID的API端点能够自动将参数解析为webpacser\UUID\UUID类型,而不是字符串,我必须在每个端点中手动将其转换为webpacser\UUID\UUID。在Laravel中有没有一种方法可以让它尝试将名为{uuid}的任何路由参数从字符串解析为WebPoster\uuid\uuid web.php use Webpatser\Uuid\Uuid; ... pub

我有一个API端点,我想将UUID传递给它。我正在使用一个名为UUID的包将UUID集成到我的应用程序中。我希望采用UUID的API端点能够自动将参数解析为
webpacser\UUID\UUID
类型,而不是
字符串
,我必须在每个端点中手动将其转换为
webpacser\UUID\UUID
。在Laravel中有没有一种方法可以让它尝试将名为
{uuid}
的任何路由参数从
字符串
解析为
WebPoster\uuid\uuid

web.php

use Webpatser\Uuid\Uuid;

...

public function test(Request $request, Uuid $uuid): RedirectResponse
{
    echo 'My UUID: ' . $uuid->string;

    return redirect()->route('home');
}
Route::get('/mycontroller/test/{uuid}',Web\MyController@test')->name('test')

MyController.php

use Webpatser\Uuid\Uuid;

...

public function test(Request $request, Uuid $uuid): RedirectResponse
{
    echo 'My UUID: ' . $uuid->string;

    return redirect()->route('home');
}
我试图通过如下URL调用上述代码:

http://localhost:8000/mycontroller/test/9ec21125-6367-1ab3-9c88-d6de3990ff81
答案是:模型绑定

添加到
App\Providers\RouteServiceProvider
中的
boot()
方法:

Route::bind('uuid',函数($value){
返回Uuid::导入($value);
});
当您从路由中访问
{uuid}
时,您将获得uuid对象,如:

Route::get('test/{uuid}',函数($uuid){
echo$uuid->string;
});
答案是:模型绑定

添加到
App\Providers\RouteServiceProvider
中的
boot()
方法:

Route::bind('uuid',函数($value){
返回Uuid::导入($value);
});
当您从路由中访问
{uuid}
时,您将获得uuid对象,如:

Route::get('test/{uuid}',函数($uuid){
echo$uuid->string;
});

我以前曾尝试过,但出现以下错误:“Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException无消息”。我也运行了
php-artisan-route:clear
php-artisan-clear编译的
,运气不好。你是如何访问这个URL的?在我最初的问题中,我发布了我使用的URL。我正在将其复制并粘贴到浏览器中。请尝试将路由更改为任意:
route::ANY('/mycontroller/test/{uuid}',Web\MyController@test')->name('test')刚刚注意到了这一点,而且它很有效!我必须在
web.php
中实现该端点的所有代码吗?或者我可以在
MyController.php
test
函数中实现它吗?我之前已经尝试过了,但我得到了以下错误:“Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException无消息”。我也运行了
php-artisan-route:clear
php-artisan-clear编译的
,运气不好。你是如何访问这个URL的?在我最初的问题中,我发布了我使用的URL。我正在将其复制并粘贴到浏览器中。请尝试将路由更改为任意:
route::ANY('/mycontroller/test/{uuid}',Web\MyController@test')->name('test')刚刚注意到了这一点,而且它很有效!我是否必须在
web.php
中实现路由内部该端点的所有代码,或者我可以在
MyController.php
test
函数中实现它?