Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ralphmrivera's avatar

Using UID column for API Resource routes instead of ID

Can a field other than id be used for API Resources? I'd like to use a uid column for the routes. I don't want to change protected $primaryKey = 'id'; in my model, but would still like to use uid in resource routes.

0 likes
3 replies
shez1983's avatar
shez1983
Best Answer
Level 23

sure it can - you will have to save that value yourself (by hooking into saved event or in your save controller method etc).. if you mean route model binding then you just need a func in your model to let laravel know (check the doc for func name)

1 like
thedejavunl's avatar

You can use an where argument in your Eloquent model in combination with firstOrFail to return an row based on the uid.

Route::get('model/{uid}', function ($uid) {
    return App\ModelName::where('uid', $uid)->firstOrFail();
}

If the UID can't be found, a 404 HTTP response is automatically sent back to the user.

ralphmrivera's avatar

Thanks so much for the help. I ended up doing this in my model:

public function getRouteKeyName()
    {
        return 'uid';
    }

And now everything works exactly like I want including my tests.

1 like

Please or to participate in this conversation.