Laravel: UUID for public, ID for the application

A nice way to obfuscate, without taking away the default ID.

Photo by Kyle Glenn on Unsplash
https://podcast.app/podcasts/47

Setting up the Database

Some databases can be configured to set an UUID into the primary key when inserting a new row. You should check this on whatever RDBMS are you using, since implementation vary between each of them.

https://podcast.app/podcast/535c4cdf-70a0-4615-82f2-443e95c86aec

Wiring the Model to the UUID

You don’t have to do anything in the Model, except for two things: hide the ID from serialization, and allow the Model to be “url-routable” using the UUID.

$podcast = Podcast::first();// This will work
echo $podcast->id; // 47
// But this won't
echo $podcast->toArray()['id']; // null
echo json_decode($podcast->toJson())->id; // ERROR
Route::get({podcast}, 'PodcastController@show');
/**
* Show the Podcast by its UUID
*
* @param \App\Podcast $podcast
* @return \Illuminate\Http\Response
/*
public function show(Podcast $podcast)
{
return response()->view('response', [
'podcast' => $podcast
]);
}

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store