Search code examples
phplaraveluuid

Laravel API endpoint with non-primitive type hinted parameter


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


Solution

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