Last Updated: February 25, 2016
· tbleckert

Laravel hidden ID

Sometimes it's smart to not expose the ID of a resource. One reason is because the ID can tell how active the site is, we don't always want this.

What I almost always do is to use Hashids. Hashids generates short hashes from numbers. Like this:

Hashids::encrypt(1); //Ri7Bi

Now, to use this automatically it's a good idea to use a Laravel accessor. But we don't want to change the ID itself (that can cause a lot of troubles). So we use a combination of the protected arrays $appends and $hidden.

class Resource extends Eloquent {

    protected $hidden   = array('id');
    protected $appends = array('token');

    public function getTokenAttribute()
        return Hashids::encrypt($this->id);


This way we hide the ID and creates a custom attributes that will be returned automatically in the collection.

What do you think?

2 Responses
Add your response

Nice. hope to use this soon. Will update if I find a nice alternative use case for it also. In my mind i am thinking replacing the id with actions or ect. will only know once I have it in front of me.

But thanx for this.

over 1 year ago ·

Cool, glad you like it. Another use case for using hashids is when you have an action that requires multiple id's, like making a relation between two resources. Imagine this url relation/create/1/2. Instead of exposing those two ID's and using only 1 token instead of two ID's, you can use Hashids like so: $token = Hashids::encrypt($first->id, $second->id); // wguB. And when you decrypt it you would get an array of the two ID's. I just need to find out a nice way the integrate it with Laravel.

over 1 year ago ·