rohitnaidu19
rohitnaidu19

Reputation: 693

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?

Upvotes: 4

Views: 1632

Answers (2)

Konstantin L
Konstantin L

Reputation: 301

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.

Upvotes: 1

Margus Pala
Margus Pala

Reputation: 8663

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

Upvotes: 1

Related Questions