Code Monkey home page Code Monkey logo

eloquent-hashids's Introduction

Using hashids instead of integer ids in urls and list items can be more appealing and clever. For more information visit hashids.org.

Eloquent-Hashids Build Status

This adds hashids to Laravel Eloquent models by encoding/decoding them on the fly rather than persisting them in the database. So no need for another database column and also higher performance by using primary keys in queries.

Features include:

  • Generating hashids for models
  • Resloving hashids to models
  • Ability to customize hashid settings for each model
  • Route binding with hashids (optional)

Installation

Install the package with Composer:

$ composer require mtvs/eloquent-hashids

Also, publish the vendor config files to your application (necessary for the dependencies):

$ php artisan vendor:publish

Setup

Base features are provided by using HasHashid trait then route binding with hashids can be added by using HashidRouting.

use Illuminate\Database\Eloquent\Model;
use Mtvs\EloquentHashids\HasHashid;
use Mtvs\EloquentHashids\HashidRouting;

Class Item extends Model
{
	use HasHashid, HashidRouting;
}

Custom Hashid Settings

It's possible to customize hashids settings for each model by overwriting getHashidsConnection(). It must return the name of a connection of vinkla/hashids that provides the desired settings.

Usage

Basics

// Generating the model hashid based on its key
$item->hashid();

// Equivalent to the above but with the attribute style
$item->hashid;

// Finding a model based on the provided hashid or
// returning null on failure
Item::findByHashid($hashid);

// Finding a model based on the provided hashid or
// throwing a ModelNotFoundException on failure
Item::findByHashidOrFail($hashid);

// Decoding a hashid to its equivalent id 
$item->hashidToId($hashid);

// Encoding an id to its equivalent hashid
$item->idToHashid($id);

// Getting the name of the hashid connection
$item->getHashidsConnection();

Add the hashid to the serialized model

Set it as default:

use Illuminate\Database\Eloquent\Model;
use Mtvs\EloquentHashids\HasHashid;

class Item extends Model
{
    use HasHashid;
    
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['hashid'];
}

or specify it specificly:

return $item->append('hashid')->toJson();

Implicit Route Bindings

If you want to resolve implicit route bindings for the model using its hahsid value you can use HashidRouting in the model.

use Illuminate\Database\Eloquent\Model;
use Mtvs\EloquentHashids\HasHashid;
use Mtvs\EloquentHashids\HashidRouting;

class Item extends Model
{
    use HasHashid, HashidRouting;
}

It overwrites getRouteKeyName(), getRouteKey() and resolveRouteBindingQuery() to use the hashids as the route keys.

It supports the Laravel's feature for customizing the key for specific routes.

Route::get('/items/{item:slug}', function (Item $item) {
    return $item;
});

Customizing The Default Route Key Name

If you want to by default resolve the implicit route bindings using another field you can overwrite getRouteKeyName() to return the field's name to the resolving process and getRouteKey() to return its value in your links.

use Illuminate\Database\Eloquent\Model;
use Mtvs\EloquentHashids\HasHashid;
use Mtvs\EloquentHashids\HashidRouting;

class Item extends Model
{
    use HasHashid, HashidRouting;

    public function getRouteKeyName()
    {
        return 'slug';
    }

    public function getRouteKey()
    {
        return $this->slug;
    }
}

You'll still be able to specify the hashid for specific routes.

Route::get('/items/{item:hashid}', function (Item $item) {
    return $item;
});

Supporting The Other Laravel's Implicit Route Binding Features

When using HashidRouting you'll still be able to use softdeletable and child route bindings.

Route::get('/items/{item}', function (Item $item) {
    return $item;
})->withTrashed();

Route::get('/user/{user}/items/{item}', function (User $user, Item $item) {
    return $item;
})->scopeBindings();

eloquent-hashids's People

Contributors

crynobone avatar mtvs avatar npostman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

eloquent-hashids's Issues

Document customization of options

Hi,

I'm new to laravel and was not able to understand from your code how I can customize some options. For example I am looking to add a padding as described here under 'Use padding to make your output ids longer'. Is it possible to do this with this extension?

Thanks,
robin

Laravel Request validation

I have generated the custom hashids of 10 digits. When i try to do the request validation it fails. Is there anything need to be done for validation.

Laravel 7 support

Please, add laravel 7 support. Currently when installing library, composer throws this error:

mtvs/eloquent-hashids v1.1.0 requires illuminate/database ~5.5.0|~5.6.0|~5.7.0|~5.8.0|^6.0

Looks like it should be easy to update since no major Eloquent changes in Laravel 7.

TypeError: Unsupported operand types: int - string

protected $appends = ['hashid'];

Appending hashid to model raises the following exception (even simple operations like Model::find(1)):

TypeError: Unsupported operand types: int - string

The TypeError disappears if I remove the $appends

I'm using PHP x64 8.1.4, Laravel 8.83.5

Wrong exception on invalid hash string

Hi
When the hash string is invalid, an InvalidArgumentException throws via the findByHashidOrFail() method. I think, It supposed to have a not found exception.

Case sensitive hashid

Hello,
Thank you for the library, I was already using vinkla/hashids and yours so simplify.

Main issue for me to use hashid is case sensitive in database, when I have 'A4cd945a' and 'a4cd945a'. find only for 'a4cd945a' and data result show 'A4cd945a', that make me a little crazy.
So I added a little code to find the hashid with, where BINARY hashid = 'a4cd945a'

This library have case sensitive for search the hashid?

Hashid as attribute

Add the hashid as an attribute to Has Hashid

public function getHashidAttribute()
{
return $this->hashid();
}

Feature proposal

I would like to add a prefix to the hashid to identify them.

For example:

  • User model: usr_xxxx
  • Order model: ord_xxxx
  • Transaction model: txn_xxxx

Do you think it is a useful feature?

Regards.

Unsupported operand types: int - string

Steps:

  1. Installed package via composer.
  2. Import/use the hashId trait
  3. In the tests, use a factory create method to make a model.
  4. On the returned value, which is an model instance, called hashId() method.
  5. Error.

`Unsupported operand types: int - string

at vendor/hashids/hashids/src/Hashids.php:203
199โ–• while (\mb_strlen($ret) < $this->minHashLength) {
200โ–• $alphabet = $this->shuffle($alphabet, $alphabet);
201โ–• $ret = \mb_substr($alphabet, $halfLength) . $ret . \mb_substr($alphabet, 0, $halfLength);
202โ–•
โžœ 203โ–• $excess = \mb_strlen($ret) - $this->minHashLength;`

minHashLength seems to be evaluating to a string. The actual ID on the record used was (int)1.

Fetch from multiple hashids

Is it possible to get() from an array of hashids?

Or perhaps access the hashidToId() method statically?

At the moment I am having to do:

$ids = [];

foreach ($hashids as $hashid) {
    array_push($ids, (new Product)->hashidToId($hashid));
}

return Product::whereIn('id', $ids)->get();

Feature request: validation rule

Iโ€™m using eloquent hashids on a number of related objects, and often I am passing a related_model_id as part of my request.

Currently Iโ€™m only validating it as string|required but it would be great to be able to validate that the model actually exists, like the exists:table,column validation rule.

Is that something youโ€™d consider adding?

Laravel 8 support

Will this be updated to support Laravel 8? The current version requires illuminate/database 7.x, so isn't compatible with Laravel 8.x. Thanks!

$item->hashidToId($hashid); Question

Hello, how are you?
First I would like to thank you for the library. I was already using vinkla/hashids, but yours already helped to dry the code.

But a question arose as to how the $item->hashidToId($hashid); method works, could you explain how to use it? Is it possible to use it without an instance of the model (as a helper)?

Thank you

P.S.: I was confused because of this $item-> I don't know where it is coming from or being instantiated. But I think it's from the model, right?

ids not getting encoded

Hi

I am using laravel 7.7.1, php 7.3.11

I have followed the instructions and installed composer eloquent-hashids module, however my ids are not getting encoded when I do a route call.

It seems I am missing something, do you have any ideas what I am missing ?

api.php is

Route::get('pages', 'PageController@index');

PageController is

class PageController extends Controller
{
    public function index()
    {
        return Page::all();
    }

Page Model is

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Mtvs\EloquentHashids\HasHashid;
use Mtvs\EloquentHashids\HashidRouting;

class Page extends Model 
{
    use HasHashid, HashidRouting;

...

when I call
GET http://{{api-url}}/pages

I was expecting

"id": <hashKey>,
"name": "My Page 1"

I still get the Id.

HTTP/1.1 200 OK
Date: Thu, 23 Apr 2020 00:53:50 GMT
Server: Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.3.11
Vary: Authorization
X-Powered-By: PHP/7.3.11
Cache-Control: no-cache, private
X-RateLimit-Limit: 500
X-RateLimit-Remaining: 499
Content-Length: 4241
Connection: close
Content-Type: application/json

[
{
"id": 1,
"name": "My Page 1"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.