PHP code example of davide7h / encoded-ids

1. Go to this page and download the library: Download davide7h/encoded-ids 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/ */

    

davide7h / encoded-ids example snippets

 artisan encoded-ids:install



namespace App\Models;

...
use Davide7h\EncodedIds\Traits\HasEncodedId;
...

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasEncodedId;
    
    ...
}

$user = User::first();
echo $user->id;         //example output: 1
echo $user->encoded_id; //example output: "ULwu08NB"

User::find(1)          //returns the User model with ID = 1;
User::find("ULwu08NB") //also returns the User with ID = 1;

...
use Davide7h\EncodedIds\Services\EncodingService;
...

EncodingService::encode(1);          //example output: "ULwu08NB"
EncodingService::decode("ULwu08NB"); //example output: 1;

//Route file:
Route::get('/users/{encoded_id}', [UserController::class, 'getUser'])

//UserController class:
public function getUser(String $encoded_id)
{
    $user = User::findOrFail($encoded_id);
    ...
}

//Route file
Route::get('/users/{user:encoded_id}', [UserController::class, 'getUser'])

//UserController
public function getUser(User $user)
{
    ....
}

config/encoded-ids.php