phplaravelstring-hashing

Laravel replace primary key with hashids for all get


Im using laravel 4.2 and I want to use hashids instead of primary key in urls. Its easy to use with a single record. If I use eager loading I need to loop through all models and replace the primary keys with hash ids.

For example. For every post I need to change the post_id with a hashid. For every comment of the post I have to do the same. For every user of the comment and so on.. Can I extend the model to return hashid by default?


Solution

  • Yes, you can extend your model with mutators. Place this method into your models, or even better into your base model which all of your models should extend.

    public function getHashidAttribute()
    {
        return your_hash_function($this->attributes['id']);
    }
    

    After that you would get hashid attribute on your models like so $post->hashid, $comment->hashid etc.