Skip to content

Instantly share code, notes, and snippets.

@DominikStyp
Last active February 1, 2024 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DominikStyp/b9ec398a085e1ed1ecb6b9d6a8ae2fe1 to your computer and use it in GitHub Desktop.
Save DominikStyp/b9ec398a085e1ed1ecb6b9d6a8ae2fe1 to your computer and use it in GitHub Desktop.
Laravel 10: user custom attributes implementation in User model

How to use

$user = User::first();

$user->setCustomField('marked_by_username', 'some_username');
$user->setCustomField('marked_date', now()->format('Y-m-d H:i:s'));

$username = $user->getCustomField('marked_by_username');

$user->deleteCustomField('marked_by_username');

this is gonna be stored in the custom_fields attribute which is TEXT in the form of JSON.

<?php
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->text('custom_attributes')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('order_buy_flow_orders', function (Blueprint $table) {
$table->dropColumn('custom_attributes');
});
}
};
<?php
class User extends Authenticatable implements JWTSubject
{
protected function customFields(): Attribute
{
return Attribute::make(
get: fn (?string $value) => (object)json_decode($value),
set: fn (array|object $value) => json_encode($value, JSON_FORCE_OBJECT),
);
}
public function getCustomField(string $name): mixed
{
return $this->custom_fields->$name ?? null;
}
public function setCustomField(string $name, mixed $value): void
{
$this->custom_fields = array_merge((array)$this->custom_fields, [ $name => $value ]);
}
public function deleteCustomField(string $name): void
{
$attributes = (array)$this->custom_fields;
if(isset($attributes[$name])){
unset($attributes[$name]);
}
$this->custom_fields = $attributes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment