4

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?

Blackus
  • 6,883
  • 5
  • 40
  • 51
rohitnaidu19
  • 673
  • 5
  • 23

2 Answers2

1

You can use Route::bind method to specify how exactly the models should be resolved from the URL segments like below.

Route::bind('post', function($value)
{
    return Post::where('hashid', $value)->first();
});

Now Laravel knows how to resolve the Eloquent Model if you use route like this

/admin/{post}/edit
Margus Pala
  • 8,433
  • 8
  • 42
  • 52
1

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.

Konstantin L
  • 191
  • 3