PHP code example of hadi-aghandeh / laravel-friendly-id

1. Go to this page and download the library: Download hadi-aghandeh/laravel-friendly-id 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/ */

    

hadi-aghandeh / laravel-friendly-id example snippets

 
// use the trait
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use HadiAghandeh\FriendlyId\Traits\FriendlyId;

class Post extends Model
{
    use FriendlyId;
}

// get encoded id
$post = Post::find(1);
$friendlyId = $post->friendly_id // = xxx-xxxx-xxx

// find the model
$post = Post::whereFriendlyId($friendlyId);

return [
 /*
     |--------------------------------------------------------------------------
     | Alphabets
     |--------------------------------------------------------------------------
     |
     | provide a alphabet string it is best if you provide a string with randomized order
     |
     */
    'alphabet' => env('FRIENDLY_ID_ALPHABET', "abcdefghijklmnopqrstuvwxyz"),

    /*
     |--------------------------------------------------------------------------
     | Encoder Name
     |--------------------------------------------------------------------------
     |
     | available option BASEN, SQIDS and WORDS
     |
     */
    'encoder' => env('FRIENDLY_ID_ENCODER', 'SQIDS'),

    /*
     |--------------------------------------------------------------------------
     | Minimum length
     |--------------------------------------------------------------------------
     |
     | This option controls the minimum length of the encoded string
     |
     */
    'length' => env('FRIENDLY_ID_LENGTH', 10),

    /*
     |--------------------------------------------------------------------------
     | Default column
     |--------------------------------------------------------------------------
     |
     | This option controls the default column that friendly id uses
     |
     */
    'column' => env('FRIENDLY_ID_COLUMN', 'id'),
];

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use HadiAghandeh\FriendlyId\Traits\FriendlyId;

class Post extends Model
{
    use FriendlyId;
}

$post = Post::find(1);
$friendlyId = $post->encodeFriendlyId();

echo $friendlyId; // e.g., "abc-def-ghi"

$decodedId = Post::decodeFriendlyId('abc-def-ghi');
echo $decodedId; // e.g., 1

$post = Post::whereFriendlyId('abc-def-ghi')->first();

$invalidId = Post::decodeFriendlyId('invalid-id'); // returns null