alhaji-aki/laravel-uuid
| Install | |
|---|---|
composer require alhaji-aki/laravel-uuid |
|
| Latest Version: | 1.0.3 |
| PHP: | ^7.3|^8.0|^8.1 |
| License: | MIT |
| Last Updated: | May 10, 2022 |
| Links: | GitHub · Packagist |
Generate slugs when saving Eloquent models
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
Installation
You can install the package via composer:
composer require alhaji-aki/laravel-uuid
Usage
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();
});
}
}
Using slugs in routes
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';
}
}
Overriding slugs
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";
Testing
composer test
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email abdulkudus2922@gmail.com instead of using the issue tracker.
Credits
This package is inspired by Spatie Laravel Sluggable.
License
The MIT License (MIT). Please see License File for more information.
Related Packages
This package allows you to easily work with UUIDs in your Laravel models.
Laravel integration for webpatser/uuid - High-performance drop-in UUID replaceme...
laravel uuid a simple, automatic UUID generator for any model based on Laravel.