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 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题
  • ¥20 materialstudio计算氢键脚本问题