1. Go to this page and download the library: Download spatie/laravel-prefixed-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/ */
spatie / laravel-prefixed-ids example snippets
// on a specific model
User::findByPrefixedId('user_fj39fj3lsmxlsl'); // returns a User model or `null`
User::findByPrefixedIdOrFail('user_fj39fj3lsmxlsl'); // returns a User model or throws `NoPrefixedModelFound`
// automatically determine the model of a given prefixed id
$user = PrefixedIds::getModelClass('user_fj39fj3lsmxlsl') // returns the right model for the id or `null`;
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\PrefixedIds\Models\Concerns\HasPrefixedId;
class YourModel extends Model
{
use HasPrefixedId;
}
Schema::create('your_models_table', function (Blueprint $table) {
$table->string('prefixed_id')->nullable()->unique();
});
return [
/*
* The attribute name used to store prefixed ids on a model
*/
'prefixed_id_attribute_name' => 'prefixed_id',
];
$model = YourModel::create();
$model->prefixed_id // returns a random id like `your_model_fekjlmsme39dmMS`
YourModel::findByPrefixedId('your_model_fekjlmsme39dmMS'); // returns an instance of `YourModel`
YourModel::findByPrefixedId('non-existing-id'); // returns null
YourModel::findByPrefixedIdOrFail('non-existing-id'); // throws `NoPrefixedModelFound`
$yourModel = Spatie\PrefixedIds\PrefixedIds::find('your_model_fekjlmsme39dmMS'); // returns an instance of `YourModel` or `null`
$otherModel = Spatie\PrefixedIds\PrefixedIds::find('other_model_3Fjmmfsmls'); // returns an instance of `OtherModel` or `null`
$otherModel = Spatie\PrefixedIds\PrefixedIds::findOrFail('other_model_3Fjmmfsmls'); // returns an instance of `OtherModel` or throws `NoPrefixedModelFound`
// generate a unique Id with a set length
Spatie\PrefixedIds\PrefixedIds::generateUniqueIdUsing(function(){
$length = 8;
return substr(md5(uniqid(mt_rand(), true)), 0, $length);
});
public function getRouteKeyName()
{
return 'prefixed_id';
}