This package provides a trait that will generate a unique uuid when saving any Eloquent model.
$model = new EloquentModel();
$model->name = 'activerecord is awesome';
$model->save();
echo $model->uuid; // outputs a uuid
You can install the package via composer:
composer require alhaji-aki/laravel-uuid
Your Eloquent models should use the AlhajiAki\LaravelUuid\HasUuid
trait.
The trait contains an abstract method getUuidColumn()
that you must implement yourself.
Your models' migrations should have a field to save the uuid to.
Here's an example of how to implement the trait:
namespace App;
use AlhajiAki\LaravelUuid\HasUuid;
use Illuminate\Database\Eloquent\Model;
class YourEloquentModel extends Model
{
use HasUuid;
/**
* Get the column to save the generated uuid to.
*/
public function getUuidColumn() : string
{
return 'uuid';
}
}
With its migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateYourEloquentModelTable extends Migration
{
public function up()
{
Schema::create('your_eloquent_models', function (Blueprint $table) {
$table->increments('id');
$table->string('uuid'); // Field name same as what you return in `getUuidColumn`
$table->string('name');
$table->timestamps();
});
}
}
To use the generated uuid in routes, remember to use Laravel's implicit route model binding:
namespace App;
use AlhajiAki\LaravelUuid\HasUuid;
use Illuminate\Database\Eloquent\Model;
class YourEloquentModel extends Model
{
use HasUuid;
/**
* Get the column to save the generated uuid to.
*/
public function getUuidColumn() : string
{
return 'uuid';
}
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'uuid';
}
}
You can also override the generated slug just by setting it to another value than the generated slug.
$model = EloquentModel::create(['name' => 'my name']); //slug is now "my-name";
$model->slug = 'my-custom-url';
$model->save(); //slug is now "my-custom-url";
composer test
Please see CONTRIBUTING for details.
If you discover any security related issues, please email abdulkudus2922@gmail.com instead of using the issue tracker.
This package is inspired by Spatie Laravel Sluggable.
The MIT License (MIT). Please see License File for more information.