Skip to main content

laravelio/laravel.io

2499 stars
6 code files
View laravelio/laravel.io on GitHub

composer.json

Open in GitHub
{
"name": "laravelio/laravel.io",
"require": {
"php": "^8.0",
"algolia/scout-extended": "^1.10",
// ...
 
"ramsey/uuid": "^4.1",
 
// ...
},
}

database/migrations/2017_10_18_193001_create_subscriptions_table.php

Open in GitHub
// In this project, UUID is a primary key of the table
 
class CreateSubscriptionsTable extends Migration
{
public function up()
{
Schema::create('subscriptions', function (Blueprint $table) {
$table->uuid('uuid');
$table->primary('uuid');
$table->integer('user_id')->unsigned();
$table->integer('subscriptionable_id');
$table->string('subscriptionable_type')->default('');
$table->timestamps();
});
 
Schema::table('subscriptions', function (Blueprint $table) {
$table->index(['user_id', 'uuid']);
});
}
}

app/Helpers/HasUuid.php

Open in GitHub
// This Trait would be added to all models that use UUID
 
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
 
trait HasUuid
{
public function uuid(): UuidInterface
{
return Uuid::fromString($this->uuid);
}
 
public function getKeyName()
{
return 'uuid';
}
 
public function getIncrementing()
{
return false;
}
 
public static function findByUuidOrFail(UuidInterface $uuid): self
{
return static::where('uuid', $uuid->toString())->firstOrFail();
}
}

app/Models/Subscription.php

Open in GitHub
use App\Helpers\HasUuid;
 
final class Subscription extends Model
{
use HasUuid;
 
// ... other model properties and methods
}

app/Jobs/CreateThread.php

Open in GitHub
// This Job creates a forum thread, and then a subscription to this thread, with UUID generated
 
use App\Models\Subscription;
use Ramsey\Uuid\Uuid;
 
final class CreateThread
{
public function handle(): Thread
{
$thread = new Thread([
'subject' => $this->subject,
'body' => $this->body,
'slug' => $this->subject,
]);
 
// Subscribe author to the thread.
$subscription = new Subscription();
$subscription->uuid = Uuid::uuid4()->toString();
$subscription->userRelation()->associate($this->author);
$subscription->subscriptionAbleRelation()->associate($thread);
 
$thread->subscriptionsRelation()->save($subscription);
 
return $thread;
}
}

routes/bindings.php

Open in GitHub
// This additional routes file overrides the default Route Model Binding rules, like UUID
 
$uuid = '[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}';
 
Route::bind('subscription', function (string $uuid) {
return App\Models\Subscription::findByUuidOrFail(Ramsey\Uuid\Uuid::fromString($uuid));
});
Route::pattern('subscription', $uuid);
 
// ... Other binding rules