PHP code example of dialloibrahima / eloquent-hashids
1. Go to this page and download the library: Download dialloibrahima/eloquent-hashids library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
dialloibrahima / eloquent-hashids example snippets
use DialloIbrahima\EloquentHashids\Hashidable;
class User extends Model
{
use Hashidable;
}
// Get the hashid
$user->hashid; // "aBcD3FgH1jKlM4nP"
// Find by hashid
User::findByHashid('aBcD3FgH1jKlM4nP');
User::findByHashidOrFail('aBcD3FgH1jKlM4nP');
// Route model binding works automatically
Route::get('/users/{user}', function (User $user) {
return $user;
});
// URL: /users/aBcD3FgH1jKlM4nP
use DialloIbrahima\EloquentHashids\Contracts\HashidableConfigInterface;
use DialloIbrahima\EloquentHashids\Hashidable;
class Invoice extends Model implements HashidableConfigInterface
{
use Hashidable;
public function hashidableConfig(): array
{
return [
'prefix' => 'inv',
'suffix' => 'v1',
'length' => 12,
'separator' => '_',
];
}
}
// Result: inv_aBcD3FgH_v1
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->hashid,
'name' => $this->name,
'email' => $this->email,
];
}
}
class User extends Model
{
use Hashidable;
public function resolveRouteBinding($value, $field = null): ?Model
{
// Your custom logic here...
// Then resolve the hashid
return $this->resolveHashidRouteBinding($value);
}
}
public function show(User $user)
{
$this->authorize('view', $user);
return $user;
}