mtvs / eloquent-hashids

On-the-fly hashids for Laravel Eloquent models. (🍰 Easy & ⚡ Fast)
292 stars 21 forks source link

TypeError: Unsupported operand types: int - string #24

Closed masroore closed 2 years ago

masroore commented 2 years ago

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

vctrtvfrrr commented 2 years ago

The same error occurs to me, but with the following scenario:

My model:

declare(strict_types=1);

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

class Flight extends Model
{
    use HasHashid, HashidRouting;

    protected $appends = ['hashid'];
}

In controller:

declare(strict_types=1);

namespace App\Http\Controllers;

class AuthController extends Controller
{
    public function index()
    {
        $user = \App\Models\User::factory()->create();

        $user->hashid;
        // or
        $user->hashid();
    }
}

This throws:

TypeError: Unsupported operand types: int - string

/path/to/laravel/vendor/hashids/hashids/src/Hashids.php:203
/path/to/laravel/vendor/mtvs/eloquent-hashids/src/HasHashid.php:48
/path/to/laravel/vendor/mtvs/eloquent-hashids/src/HasHashid.php:24
/path/to/laravel/app/Http/Controllers/ItemController.php:13
masroore commented 2 years ago

For now, remove hashid from $appends and manually set the hashid in the serialized model.

The error occurs in the upstream vinkla/hashids package:

$excess = \mb_strlen($ret) - $this->minHashLength;

Somehow $minHashLength is a string...

mtvs commented 2 years ago

Go to the hashids config file and set the length key to a desired number. The default value is a placeholder string. Probably an issue can be opened into the vinkla/hashids.

masroore commented 2 years ago

Did that already before submitting this issue. Length is set as an integer value. The error persists still.

masroore commented 2 years ago

https://github.com/vinkla/hashids/issues/178

mtvs commented 2 years ago

Under the hood, for encoding and decoding the hashids, an object from Hashids\Hashids is created and three values are passed to it including the length which all are read from the hashids config.

No special operation is done on those values, so the only issue can be the config values themselves.

Make sure to set the length value in the config file for the default connection and for all custom connections you have possibly created.

Finally to debug, you can go to the line that the error happens and simply dump the value that creates the error.