### Install Laravel Model HashId Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Install the package using Composer. After installation, publish the configuration file to customize settings. ```bash composer require deligoez/laravel-model-hashid ``` ```bash php artisan vendor:publish --provider="Deligoez\LaravelModelHashId\LaravelModelHashIdServiceProvider" --tag="config" ``` -------------------------------- ### Run Tests Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Execute the package's test suite using Composer. This command runs a full quality gate including Rector, Pint, PHPStan, and Pest to ensure code quality and correctness. ```bash composer test ``` -------------------------------- ### Publish Configuration File Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Publish the package's configuration file to your application's config directory using the provided Artisan command. This allows for customization of Hash ID generation and behavior. ```bash php artisan vendor:publish --provider="Deligoez\LaravelModelHashId\LaravelModelHashIdServiceProvider" --tag="config" ``` -------------------------------- ### Artisan Commands for HashId Encoding and Decoding Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Two Artisan commands provide CLI access to Hash Id encoding and decoding for debugging and scripting purposes. ```bash # hashid:encode {model} {id} # Encodes an integer key to the model's Hash Id and prints it. php artisan hashid:encode "App\Models\User" 1234 # Output: use_kqYZeLgo8xDmN ``` ```bash # hashid:decode {hashid} {model?} # Decodes a Hash Id and prints a table of key, model, prefix, and separator. # With explicit model class: php artisan hashid:decode "use_kqYZeLgo8xDmN" "App\Models\User" # +-----------+---------------------+ # | Field | Value | # +-----------+---------------------+ # | Key | 1234 | # | Model | App\Models\User | # | Prefix | use | # | Separator | _ | # +-----------+---------------------+ # Without model — auto-detects from model_generators config: php artisan hashid:decode "use_kqYZeLgo8xDmN" # Both commands return exit code 0 on success, 1 on failure (class not found, trait missing, or decode failure). ``` -------------------------------- ### Extend ConfigParameters (v3) vs Use Constants (v4) Source: https://github.com/deligoez/laravel-model-hashid/blob/main/UPGRADE.md Before v4, extending `ConfigParameters` was possible. In v4, this class is `final` with a private constructor, so you should use its constants directly. ```php // Before (v3): extending was possible class MyConfigParameters extends ConfigParameters { ... } ``` ```php // After (v4): use constants directly ConfigParameters::SALT; ConfigParameters::LENGTH; ``` -------------------------------- ### Encode and Decode with HashId Utility Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Use the static `HashId` methods for generic encoding and decoding. Parameters like prefix, separator, salt, length, and alphabet can be customized or omitted to use global configuration. ```php use Deligoez\LaravelModelHashId\Support\HashId; // Encode — all parameters except $id are optional HashId::encode(1234); // 'kqYZeLgo8xDmN' (uses config salt, length, alphabet; no prefix) HashId::encode(1234, prefix: 'tok', separator: '_'); // 'tok_kqYZeLgo8xDmN' HashId::encode(1234, salt: 'custom-salt', length: 8, alphabet: 'abcdefghijklmnop'); // short hash with custom generator settings // Decode — returns int or null on failure HashId::decode('kqYZeLgo8xDmN'); // 1234 HashId::decode('tok_kqYZeLgo8xDmN', prefix: 'tok', separator: '_'); // 1234 HashId::decode('tok_kqYZeLgo8xDmN', prefix: 'wrong'); // null — prefix mismatch ``` ```php // Build a standalone Hashids generator instance $generator = HashId::buildGenerator(salt: 'my-salt', length: 10); $raw = $generator->encode(99); // encode directly via hashids/hashids API $generator->decode($raw); // [99] ``` -------------------------------- ### Build a Standalone Hash ID Generator Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Create a standalone Hash ID generator instance with custom salt and length for specific encoding/decoding needs. ```php use Deligoez\LaravelModelHashId\Support\HashId; // Build a standalone generator $generator = HashId::buildGenerator(salt: 'my-salt', length: 10); ``` -------------------------------- ### Add hashId() Macro to Blueprint for Migrations Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Utilize the `hashId()` macro on the `Blueprint` class within migrations to create columns for storing Hash IDs. Supports default and custom column names. ```php Schema::create('users', function (Blueprint $table) { $table->id(); $table->hashId(); // nullable, unique string column (default: 'hash_id') $table->hashId('custom_hash'); // custom column name $table->timestamps(); }); ``` -------------------------------- ### Encode Integers to Hash IDs with HashId Utility Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Use the `HashId` utility class to encode integers into Hash IDs. Supports default configuration, custom prefixes, separators, salts, lengths, and alphabets. ```php use Deligoez\LaravelModelHashId\Support\HashId; // Encode with default config HashId::encode(1234); // 'kqYZeLgo...' // Encode with prefix and separator HashId::encode(1234, prefix: 'tok', separator: '_'); // 'tok_kqYZeLgo...' // Encode with custom salt, length, and alphabet HashId::encode(1234, salt: 'custom', length: 8); ``` -------------------------------- ### Artisan Commands Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Two Artisan commands provide CLI access to Hash Id encoding and decoding for debugging and scripting purposes. ```APIDOC ## Artisan Commands Two Artisan commands provide CLI access to Hash Id encoding and decoding for debugging and scripting. ```bash # hashid:encode {model} {id} # Encodes an integer key to the model's Hash Id and prints it. php artisan hashid:encode "App\Models\User" 1234 # Output: use_kqYZeLgo8xDmN # hashid:decode {hashid} {model?} # Decodes a Hash Id and prints a table of key, model, prefix, and separator. # With explicit model class: php artisan hashid:decode "use_kqYZeLgo8xDmN" "App\Models\User" # +-----------+---------------------+ # | Field | Value | # +-----------+---------------------+ # | Key | 1234 | # | Model | App\Models\User | # | Prefix | use | # | Separator | _ | # +-----------+---------------------+ # Without model — auto-detects from model_generators config: php artisan hashid:decode "use_kqYZeLgo8xDmN" # Both commands return exit code 0 on success, 1 on failure (class not found, # trait missing, or decode failure). ``` ``` -------------------------------- ### Query Builder Mixins Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Provides seven query builder methods mixed into `Illuminate\Database\Eloquent\Builder` for models using `HasHashId`, mirroring Laravel's find/where API. ```APIDOC ## Query Builder Mixins Seven query builder methods are mixed into `Illuminate\Database\Eloquent\Builder` for all models using `HasHashId`, mirroring Laravel's built-in find/where API. ```php use App\Models\User; // findByHashId($hashId, $columns = ['*']) // Returns the matching model or null — equivalent to find() with integer key $user = User::findByHashId('use_kqYZeLgo8xDmN'); // User|null // findManyByHashId($hashIds, $columns = ['*']) // Accepts an array or Arrayable; returns a Collection $users = User::findManyByHashId(['use_kqYZeLgo8xDmN', 'use_ZeLgokqY9abc']); // Illuminate\Database\Eloquent\Collection // findOrFailByHashId($hashId, $columns = ['*']) // Throws ModelNotFoundException if not found $user = User::findOrFailByHashId('use_kqYZeLgo8xDmN'); // findOrByHashId($hashId, $columns = ['*'], ?Closure $callback = null) // Executes callback (or returns a new model) when record is not found $user = User::findOrByHashId('use_kqYZeLgo8xDmN', ['*'], function () { return new User(['name' => 'Guest']); }); // findOrNewByHashId($hashId, $columns = ['*']) // Returns the model or a fresh unsaved instance if not found $user = User::findOrNewByHashId('use_kqYZeLgo8xDmN'); // whereHashId($hashId) — adds a whereKey() clause; chainable $query = User::whereHashId('use_kqYZeLgo8xDmN') ->with('posts') ->first(); // whereHashIdNot($hashId) — adds a whereKeyNot() clause; chainable $otherUsers = User::whereHashIdNot('use_kqYZeLgo8xDmN')->get(); ``` ``` -------------------------------- ### Query Eloquent Models Using Hash IDs Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Utilize the provided query builder functions to find models using their HashIds. These methods include `findByHashId`, `findManyByHashId`, `findOrFailByHashId`, `findOrByHashId`, `findOrNewByHashId`, `whereHashId`, and `whereHashIdNot`. ```php // Find a model by its Hash Id User::findByHashId('user_kqYZeLgo'); // Find multiple models by their Hash Ids User::findManyByHashId(['user_kqYZeLgo', 'user_ZeLgokqY']); // Find or throw ModelNotFoundException User::findOrFailByHashId('user_kqYZeLgo'); // Find or execute a callback User::findOrByHashId('user_kqYZeLgo'); // Find or return a new model instance User::findOrNewByHashId('user_kqYZeLgo'); // Where clause using Hash Id User::whereHashId('user_kqYZeLgo'); // Where not clause using Hash Id User::whereHashIdNot('user_kqYZeLgo'); ``` -------------------------------- ### Rename Config::checkIfModelClassExist() to Config::checkIfModelClassExists() Source: https://github.com/deligoez/laravel-model-hashid/blob/main/UPGRADE.md The method `Config::checkIfModelClassExist()` has been renamed to `Config::checkIfModelClassExists()` for a grammatical correction. Update your calls accordingly. ```php // Before (v3) Config::checkIfModelClassExist($model); ``` ```php // After (v4) Config::checkIfModelClassExists($model); ``` -------------------------------- ### Define Route with Hash ID Model Binding Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Define a route that utilizes Hash ID model binding. The {hash_id} parameter will be resolved to an instance of the User model. ```php // GET /users/user_kqYZeLgo Route::get('/users/{hash_id}', function (User $user) { return $user; }); ``` -------------------------------- ### Configure Laravel Model HashId Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Global and per-model Hash Id generation settings are managed in the `config/model-hashid.php` file. Key parameters include salt, length, alphabet, prefix length, prefix casing, separator, and database column. ```php // config/model-hashid.php return [ // Secret salt — MUST be changed before deploying. Reads from HASHID_SALT env var. 'salt' => env('HASHID_SALT', 'your-secret-salt-string'), // Length of the raw Hash Id (excluding prefix and separator). Default: 13 'length' => 13, // Alphabet for Hash Id generation — must have at least 16 unique characters, no spaces. 'alphabet' => 'abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ234567890', // Number of characters from the short class name used as prefix. // -1 = full short class name, 0 = no prefix. Default: 3 'prefix_length' => 3, // Prefix casing. Options: 'lower', 'upper', 'camel', 'snake', 'kebab', // 'title', 'studly', 'plural_studly'. Default: 'lower' 'prefix_case' => 'lower', // Separator placed between prefix and raw Hash Id. Default: '_' 'separator' => '_', // Database column name used by the SavesHashId trait. Default: 'hash_id' 'database_column' => 'hash_id', // Per-model overrides — any key above can be set per model class. // A special 'prefix' key sets a fully custom prefix string (bypasses generation). 'model_generators' => [ App\Models\User::class => [ 'salt' => 'user-specific-salt', 'length' => 8, 'prefix_length' => -1, // full short class name ("User") 'separator' => '-', ], App\Models\Post::class => [ 'prefix' => 'article', // fixed custom prefix, ignores prefix_length/prefix_case ], ], ]; ``` -------------------------------- ### Encode Key to Hash ID using Artisan Command Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Use the `php artisan hashid:encode` command to convert a model's integer key to its corresponding Hash ID. Requires specifying the model class and the integer key. ```bash php artisan hashid:encode "App\Models\User" 1234 ``` -------------------------------- ### Use HashIdCast for Model Attribute Casting Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Apply the `HashIdCast` to model attributes to automatically handle the conversion between integers and Hash IDs during attribute retrieval and setting. ```php use Deligoez\LaravelModelHashId\Casts\HashIdCast; class User extends Model { use HasHashId; protected $casts = [ 'hash_id' => HashIdCast::class, ]; } ``` -------------------------------- ### Configure Model Generators Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Override global Hash ID configuration options on a per-model basis within the `model_generators` array in your application's configuration file. This allows for specific settings like custom salts, lengths, or prefixes for individual models. ```php 'model_generators' => [ App\Models\User::class => [ 'salt' => 'user-specific-salt', 'length' => 8, 'prefix_length' => -1, // full class name as prefix 'separator' => '-', ], App\Models\Post::class => [ 'prefix' => 'article', // custom prefix (not generated from class name) ], ] ``` -------------------------------- ### Decode Hash IDs with HashId Utility Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Decode Hash IDs back to their original integer values using the `HashId` utility class. Supports custom prefixes. ```php use Deligoez\LaravelModelHashId\Support\HashId; // Decode HashId::decode('tok_kqYZeLgo...', prefix: 'tok'); // 1234 ``` -------------------------------- ### Register Custom Model Key in RouteServiceProvider Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Register a custom model key for explicit binding in your RouteServiceProvider to enable route model binding with Hash IDs. ```php Route::model('hash_id', User::class); ``` -------------------------------- ### getRouteKey() Return Type Change (v3 vs v4) Source: https://github.com/deligoez/laravel-model-hashid/blob/main/UPGRADE.md The `getRouteKey()` method's return type has changed from `string` to `mixed` in v4. This change accommodates cases where the model has not been saved, resulting in a `null` hash ID, and prevents potential `TypeError` exceptions. ```php // Before (v3): returned string public function getRouteKey(): string ``` ```php // After (v4): returns mixed public function getRouteKey(): mixed ``` -------------------------------- ### Enable Route Model Binding with Hash IDs Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Incorporate the `HasHashIdRouting` trait into your Eloquent models to seamlessly use HashIds for route model binding. This allows Laravel to resolve models directly from HashIds in your routes. ```php use Illuminate\Database\Eloquent\Model; use Deligoez\LaravelModelHashId\Traits\HasHashIdRouting; class User extends Model { use HasHashIdRouting; } ``` ```php // GET /users/user_kqYZeLgo Route::get('/users/{user}', function (User $user) { return $user; }); ``` -------------------------------- ### Mutable HashIdDTO (v3) vs Immutable (v4) Source: https://github.com/deligoez/laravel-model-hashid/blob/main/UPGRADE.md In v3, `HashIdDTO` properties were mutable. In v4, it is a `readonly` class, meaning its properties cannot be modified after construction. ```php // Before (v3): properties were mutable $dto = new HashIdDTO(...); $dto->prefix = 'new'; // worked ``` ```php // After (v4): properties are immutable $dto = new HashIdDTO(...); $dto->prefix = 'new'; // Error: Cannot modify readonly property ``` -------------------------------- ### Decode Hash ID to Integer Key using Artisan Command Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Use the `php artisan hashid:decode` command to convert a Hash ID back to its original integer key. You can explicitly provide the model class or let it auto-detect. ```bash # Decode a Hash Id (with explicit model) php artisan hashid:decode "user_kqYZeLgo" "App\Models\User" # Decode a Hash Id (auto-detect model from registered generators) php artisan hashid:decode "user_kqYZeLgo" ``` -------------------------------- ### Query Builder Mixins for HashId Operations Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Seven query builder methods are mixed into Illuminate\Database\Eloquent\Builder for models using HasHashId, mirroring Laravel's find/where API. ```php use App\Models\User; // findByHashId($hashId, $columns = ['*']) // Returns the matching model or null — equivalent to find() with integer key $user = User::findByHashId('use_kqYZeLgo8xDmN'); // User|null ``` ```php // findManyByHashId($hashIds, $columns = ['*']) // Accepts an array or Arrayable; returns a Collection $users = User::findManyByHashId(['use_kqYZeLgo8xDmN', 'use_ZeLgokqY9abc']); // Illuminate\Database\Eloquent\Collection ``` ```php // findOrFailByHashId($hashId, $columns = ['*']) // Throws ModelNotFoundException if not found $user = User::findOrFailByHashId('use_kqYZeLgo8xDmN'); ``` ```php // findOrByHashId($hashId, $columns = ['*'], ?Closure $callback = null) // Executes callback (or returns a new model) when record is not found $user = User::findOrByHashId('use_kqYZeLgo8xDmN', ['*'], function () { return new User(['name' => 'Guest']); }); ``` ```php // findOrNewByHashId($hashId, $columns = ['*']) // Returns the model or a fresh unsaved instance if not found $user = User::findOrNewByHashId('use_kqYZeLgo8xDmN'); ``` ```php // whereHashId($hashId) — adds a whereKey() clause; chainable $query = User::whereHashId('use_kqYZeLgo8xDmN') ->with('posts') ->first(); ``` ```php // whereHashIdNot($hashId) — adds a whereKeyNot() clause; chainable $otherUsers = User::whereHashIdNot('use_kqYZeLgo8xDmN')->get(); ``` -------------------------------- ### Eloquent Attribute Casting with HashIdCast Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Implement `HashIdCast` in your Eloquent model to automatically handle Hash ID conversion for a specific attribute. It converts integers to full Hash IDs on write and passes strings or null through. ```php use Illuminate\Database\Eloquent\Model; use Deligoez\LaravelModelHashId\Traits\HasHashId; use Deligoez\LaravelModelHashId\Casts\HashIdCast; class Token extends Model { use HasHashId; protected $casts = [ 'hash_id' => HashIdCast::class, ]; } // Assigning an integer triggers Hash Id generation: $token = new Token(); $token->id = 55; $token->hash_id = 55; // cast calls Generator::forModel($model) → 'tok_aBcD1234xYz' // Assigning a string passes through: $token->hash_id = 'tok_aBcD1234xYz'; // stored as-is // Assigning null stores null: $token->hash_id = null; // stored as null // Reading always returns the stored string (no re-encoding): $token->hash_id; // 'tok_aBcD1234xYz' ``` -------------------------------- ### HashIdExists Validation Rule for Database Existence Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Use HashIdExists to decode a Hash Id to an integer key and query the database to confirm the record exists. This is the Hash Id equivalent of Laravel's built-in exists rule. ```php use Deligoez\LaravelModelHashId\Rules\HashIdExists; // In a FormRequest: class DeleteUserRequest extends FormRequest { public function rules(): array { return [ 'user_id' => ['required', 'string', new HashIdExists(App\Models\User::class)], ]; } } ``` ```php // With Validator facade: $validator = Validator::make( ['user_id' => 'use_kqYZeLgo8xDmN'], ['user_id' => [new HashIdExists(App\Models\User::class)]] ); // Fails with "The selected user_id is invalid." when: // - value is not a string or is empty // - Hash Id cannot be decoded (keyFromHashId returns null) // - decoded key does not exist in the database ``` ```php // Combine with ValidHashId for layered validation (format check first, DB check second): $rules = [ 'user_id' => [ 'required', new ValidHashId(App\Models\User::class), new HashIdExists(App\Models\User::class), ], ]; ``` -------------------------------- ### Use SerializesHashId Trait for Primary Key Serialization Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Incorporate the `SerializesHashId` trait into your model to automatically replace the primary key with its Hash ID representation in serialized output (arrays and JSON). ```php use Deligoez\LaravelModelHashId\Traits\SerializesHashId; class User extends Model { use HasHashId; use SerializesHashId; } $user = User::find(1234); $user->toArray(); // ['id' => 'user_kqYZeLgo', 'name' => 'John', ...] $user->toJson(); // {"id":"user_kqYZeLgo","name":"John",...} ``` -------------------------------- ### Replace Primary Key with Hash Id in Serialization Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Use `SerializesHashId` to override the `toArray()` method, ensuring that the primary key field in serialized output (like JSON) contains the Hash Id instead of the raw integer. ```php use Illuminate\Database\Eloquent\Model; use Deligoez\LaravelModelHashId\Traits\HasHashId; use Deligoez\LaravelModelHashId\Traits\SerializesHashId; class User extends Model { use HasHashId; use SerializesHashId; } ``` ```php $user = User::find(1234); // toArray() replaces the 'id' value with the Hash Id: $user->toArray(); // [ // 'id' => 'use_kqYZeLgo8xDmN', ← integer replaced by Hash Id // 'name' => 'Alice', // 'email' => 'alice@example.com', // ... // ] ``` ```php // toJson() / response()->json($user) are affected the same way: $user->toJson(); // {"id":"use_kqYZeLgo8xDmN","name":"Alice","email":"alice@example.com",...} ``` ```php // $hidden and $visible attributes are respected as normal. ``` -------------------------------- ### Enable HashId Routing for Eloquent Models Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Use `HasHashIdRouting` to make Laravel resolve model bindings from Hash Id URL segments instead of integer keys. This trait overrides `getRouteKey()` and `resolveRouteBinding()`. ```php use Illuminate\Database\Eloquent\Model; use Deligoez\LaravelModelHashId\Traits\HasHashId; use Deligoez\LaravelModelHashId\Traits\HasHashIdRouting; class User extends Model { use HasHashId; use HasHashIdRouting; } ``` ```php // routes/web.php — Implicit binding: GET /users/use_kqYZeLgo8xDmN Route::get('/users/{user}', function (User $user) { // $user is resolved from the Hash Id in the URL — no manual decoding needed return response()->json([ 'id' => $user->id, // 1234 'hashId' => $user->hashId, // 'use_kqYZeLgo8xDmN' 'name' => $user->name, ]); }); ``` ```php // Explicit binding in RouteServiceProvider: Route::model('hash_id', User::class); ``` ```php // GET /users/use_kqYZeLgo8xDmN Route::get('/users/{hash_id}', function (User $user) { return $user; }); ``` ```php // getRouteKey() returns the Hash Id, so route() helpers generate correct URLs: route('users.show', $user); // https://app.test/users/use_kqYZeLgo8xDmN ``` -------------------------------- ### Add HashId Column to Migrations Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Use the `Blueprint::hashId()` macro in your Laravel migrations to easily add a nullable, unique string column for storing Hash IDs. The column name defaults to 'hash_id' but can be customized. ```php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->hashId(); // adds nullable unique 'hash_id' column $table->hashId('public_id'); // custom column name $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('users'); } }; // Equivalent to: $table->string('hash_id')->nullable()->unique(); ``` -------------------------------- ### Use HasHashId Trait for Hash Id Generation Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Add the `HasHashId` trait to Eloquent models to enable computed `hashId` and `hashIdRaw` attributes, and a static `keyFromHashId()` method for decoding. Ensure the model has a primary key for Hash Id generation. ```php use Illuminate\Database\Eloquent\Model; use Deligoez\LaravelModelHashId\Traits\HasHashId; class User extends Model { use HasHashId; } // --- Encoding --- $user = User::find(1234); $user->hashId; // 'use_kqYZeLgo8xDmN' — full Hash Id (prefix + separator + raw) $user->hashIdRaw; // 'kqYZeLgo8xDmN' — raw Hash Id only (no prefix/separator) // Unsaved model returns null $unsaved = new User(); $unsaved->hashId; // null $unsaved->hashIdRaw; // null // --- Decoding --- User::keyFromHashId('use_kqYZeLgo8xDmN'); // 1234 (int) User::keyFromHashId('invalid_hash'); // null — wrong prefix or undecipherable User::keyFromHashId('pos_kqYZeLgo8xDmN'); // null — prefix belongs to another model ``` -------------------------------- ### Use SavesHashId Trait for Automatic Hash ID Persistence Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Add the `SavesHashId` trait to your Eloquent model to automatically persist Hash IDs to the database. This is optional and requires configuring the `database_column`. ```php use Illuminate\Database\Eloquent\Model; use Deligoez\LaravelModelHashId\Traits\SavesHashId; class User extends Model { use SavesHashId; } ``` -------------------------------- ### Persist Hash Id to Database with `SavesHashId` Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt The `SavesHashId` trait automatically writes the generated Hash Id to a specified database column after a model is first inserted. Ensure a corresponding column exists in your database. ```php use Illuminate\Database\Eloquent\Model; use Deligoez\LaravelModelHashId\Traits\HasHashId; use Deligoez\LaravelModelHashId\Traits\SavesHashId; class User extends Model { use HasHashId; use SavesHashId; // writes hashId to 'hash_id' column after creation } ``` ```php // Migration — add the column to the table: Schema::table('users', function (Blueprint $table) { $table->string('hash_id')->nullable()->unique()->after('id'); }); ``` ```php $user = User::create(['name' => 'Alice']); // After creation, $user->hash_id === 'use_kqYZeLgo8xDmN' // The extra saveQuietly() call does not fire model events a second time. ``` ```php // Look up by stored column value: $found = User::where('hash_id', 'use_kqYZeLgo8xDmN')->firstOrFail(); ``` -------------------------------- ### Add HasHashId Trait to Eloquent Model Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Use the `HasHashId` trait in your Eloquent models to enable HashId generation and retrieval. This provides `hashId` and `hashIdRaw` attributes, and a `keyFromHashId()` static method. ```php use Illuminate\Database\Eloquent\Model; use Deligoez\LaravelModelHashId\Traits\HasHashId; class User extends Model { use HasHashId; } ``` ```php $user = User::find(1234); $user->hashId; // 'user_kqYZeLgo' $user->hashIdRaw; // 'kqYZeLgo' User::keyFromHashId('user_kqYZeLgo'); // 1234 ``` -------------------------------- ### ValidHashId Validation Rule Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Verifies that a value is a structurally valid Hash Id, optionally checking that it decodes against a specific model's prefix and salt without performing a database query. ```APIDOC ## `ValidHashId` Validation Rule — Format Validation `ValidHashId` verifies that a value is a structurally valid Hash Id, optionally checking that it decodes against a specific model's prefix and salt. No database query is performed. ```php use Deligoez\LaravelModelHashId\Rules\ValidHashId; // In a FormRequest or manual Validator: $rules = [ // Generic: any decodable Hash Id matching global config format 'token' => ['required', 'string', new ValidHashId()], // Model-specific: must decode correctly for the User model // (checks prefix match + successful decode — no DB hit) 'user_id' => ['required', 'string', new ValidHashId(App\Models\User::class)], ]; // Model must use HasHashId, otherwise an InvalidArgumentException is thrown immediately: try { $rule = new ValidHashId(App\Models\ModelWithoutTrait::class); } catch (\InvalidArgumentException $e) { // "The model [App\Models\ModelWithoutTrait] must use the HasHashId trait." } // Usage with Validator facade: $validator = Validator::make( ['user_id' => 'use_kqYZeLgo8xDmN'], ['user_id' => [new ValidHashId(App\Models\User::class)]] ); $validator->passes(); // true if hash decodes; false with message "The user_id must be a valid hash id." ``` ``` -------------------------------- ### HashIdExists Validation Rule Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Decodes the Hash Id to an integer key and queries the database to confirm the record exists. It is the Hash Id equivalent of Laravel's built-in `exists` rule. ```APIDOC ## `HashIdExists` Validation Rule — Database Existence Check `HashIdExists` decodes the Hash Id to an integer key and queries the database to confirm the record exists. It is the Hash Id equivalent of Laravel's built-in `exists` rule. ```php use Deligoez\LaravelModelHashId\Rules\HashIdExists; // In a FormRequest: class DeleteUserRequest extends FormRequest { public function rules(): array { return [ 'user_id' => ['required', 'string', new HashIdExists(App\Models\User::class)], ]; } } // With Validator facade: $validator = Validator::make( ['user_id' => 'use_kqYZeLgo8xDmN'], ['user_id' => [new HashIdExists(App\Models\User::class)]] ); // Fails with "The selected user_id is invalid." when: // - value is not a string or is empty // - Hash Id cannot be decoded (keyFromHashId returns null) // - decoded key does not exist in the database // Combine with ValidHashId for layered validation (format check first, DB check second): $rules = [ 'user_id' => [ 'required', new ValidHashId(App\Models\User::class), new HashIdExists(App\Models\User::class), ], ]; ``` ``` -------------------------------- ### Use HashIdExists Rule in Validation Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Integrate the `HashIdExists` rule into your Laravel validation rules to check if a provided Hash ID corresponds to an existing database record. Ensure the model you are referencing uses the `HasHashId` trait. ```php use Deligoez\LaravelModelHashId\Rules\HashIdExists; 'user_id' => [ new HashIdExists(User::class) ] ``` -------------------------------- ### Validate Hash ID Format with ValidHashId Rule Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Use the `ValidHashId` validation rule to check if a given value is a correctly formatted Hash ID. It can optionally validate against a specific model by checking if the Hash ID decodes to a valid model instance. ```php use Deligoez\LaravelModelHashId\Rules\ValidHashId; // Generic: any decodable Hash Id 'token' => [new ValidHashId] // Model-specific: must decode for User model 'user_id' => [new ValidHashId(User::class)] ``` -------------------------------- ### ValidHashId Validation Rule for Format Validation Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt Use ValidHashId to ensure a value is a structurally valid Hash Id. Optionally, check if it decodes against a specific model's prefix and salt without performing a database query. ```php use Deligoez\LaravelModelHashId\Rules\ValidHashId; // In a FormRequest or manual Validator: $rules = [ // Generic: any decodable Hash Id matching global config format 'token' => ['required', 'string', new ValidHashId()], // Model-specific: must decode correctly for the User model // (checks prefix match + successful decode — no DB hit) 'user_id' => ['required', 'string', new ValidHashId(App\Models\User::class)], ]; ``` ```php // Model must use HasHashId, otherwise an InvalidArgumentException is thrown immediately: try { $rule = new ValidHashId(App\Models\ModelWithoutTrait::class); } catch (\InvalidArgumentException $e) { // "The model [App\Models\ModelWithoutTrait] must use the HasHashId trait." } ``` ```php // Usage with Validator facade: $validator = Validator::make( ['user_id' => 'use_kqYZeLgo8xDmN'], ['user_id' => [new ValidHashId(App\Models\User::class)]] ); $validator->passes(); // true if hash decodes; false with message "The user_id must be a valid hash id." ``` -------------------------------- ### Decrypt Hash IDs in Form Requests with DecryptsHashIds Trait Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Employ the `DecryptsHashIds` trait in your `FormRequest` classes to automatically convert Hash ID inputs to their integer equivalents after validation. Define the mapping between input keys and models in the `$hashIds` property. ```php use Deligoez\LaravelModelHashId\Traits\DecryptsHashIds; class UpdatePostRequest extends FormRequest { use DecryptsHashIds; protected array $hashIds = [ 'user_id' => User::class, 'post_id' => Post::class, ]; public function rules(): array { return [ 'user_id' => ['required', new ValidHashId(User::class)], 'post_id' => ['required', new ValidHashId(Post::class)], ]; } } // In your controller, $request->user_id is now an integer ``` -------------------------------- ### Output Model Hash ID in Blade Templates with @hashid Directive Source: https://github.com/deligoez/laravel-model-hashid/blob/main/README.md Use the `@hashid` Blade directive to conveniently output a model's Hash ID within your Blade views. The output is automatically escaped for XSS safety. ```blade {{ $user->name }} ``` -------------------------------- ### Auto-decode Hash Ids in Form Requests Source: https://context7.com/deligoez/laravel-model-hashid/llms.txt The `DecryptsHashIds` trait automatically converts Hash Id strings to integer keys within a `FormRequest` by hooking into `passedValidation()`. Both `input()` and `validated()` will return decoded integers. ```php use Illuminate\Foundation\Http\FormRequest; use Deligoez\LaravelModelHashId\Traits\DecryptsHashIds; use Deligoez\LaravelModelHashId\Rules\ValidHashId; class UpdatePostRequest extends FormRequest { use DecryptsHashIds; // Map field name → model class whose HasHashId trait will decode it protected array $hashIds = [ 'user_id' => App\Models\User::class, 'post_id' => App\Models\Post::class, ]; public function rules(): array { return [ 'user_id' => ['required', new ValidHashId(App\Models\User::class)], 'post_id' => ['required', new ValidHashId(App\Models\Post::class)], ]; } } ``` ```php // In the controller — both input() and validated() return decoded integer keys: class PostController extends Controller { public function update(UpdatePostRequest $request, Post $post): JsonResponse { $userId = $request->user_id; // int, e.g. 42 (was 'use_kqYZeLgo...') $postId = $request->post_id; // int, e.g. 7 (was 'pos_abcXYZ...') $data = $request->validated(); // ['user_id' => 42, 'post_id' => 7] $post->update(['user_id' => $userId]); return response()->json($post); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.