drdr123456 2018-05-27 15:31
浏览 89
已采纳

具有非基本类型提示参数的Laravel API端点

I have an API endpoint that I want to pass a UUID to. I am using a package called Laravel-UUID to integrate UUID's into my application. I would like my API endpoints that take a UUID to automatically parse the parameter as a Webpatser\Uuid\Uuid type instead of a string that I have to manually convert to a Webpatser\Uuid\Uuid in each of my endpoints. Is there a way in Laravel to make it attempt to parse any route parameter named {uuid} from a string to a Webpatser\Uuid\Uuid?

web.php

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');
}

I am attempting to call the above code via a URL like:

http://localhost:8000/mycontroller/test/9ec21125-6367-1ab3-9c88-d6de3990ff81

  • 写回答

1条回答 默认 最新

  • dpzff20644 2018-05-27 15:58
    关注

    The answer is: model binding.

    Add to boot() method in your App\Providers\RouteServiceProvider:

    Route::bind('uuid', function ($value) {
        return Uuid::import($value);
    });
    

    And when you access {uuid} in from your route you will get Uuid object, like:

    Route::get('test/{uuid}', function($uuid) {
    
        echo $uuid->string;
    
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用