Support the ongoing development of Laravel.io →
Database Eloquent

I want to add an EAV model to my app. So I made these tables to do that:

Schema::create('attributes', function(Blueprint $table)
{
	$table->increments('id');
	$table->string('entity');	// this will contain the model class name, for example "App\User"
	$table->string('name');
	$table->smallInteger('index')->unsigned();
	$table->enum('type',
			[
				'text',
				'number',
				'date',
				'time',
				'datetime',
				'options'
			]
		)->default('text');
	$table->string('min');
	$table->string('max');
	$table->string('step');
	$table->json('options');
	$table->boolean('filterable')->default(true);
});

Schema::create('attribute_values', function(Blueprint $table)
{
	$table->integer('attribute_id')->unsigned();
	$table->integer('attributable_id')->unsigned();	// this will contain the id of the user for example
	$table->text('value');
	$table->primary(['attribute_id', 'attributable_id']);
	$table->foreign('attribute_id')
		  ->references('id')
		  ->on('attributes')
		  ->onDelete('cascade');
});

Now what I would like to do is make a trait that I can add to my models called Attributable. This trait should do a few things, but I think if I can learn how to make one of those features with a little bit of help then I can make the other ones without help.

So the feature I'd like a little help with the following. Imagine you add this trait to a user model which by itself has a username column and a password column. And now with this trait you are also adding a "hair color" attribute and an "age" attribute. I want, when one uses $user->find(1)->toArray() this to be returned:

[
    'id' => 1,
    'username' => 'admin',
    'password' => '******',
    'attributes' => [
        'hair color' => 'red',
        'age' => '28'
    ]
]

I honestly have no idea how to do that and I can't find any tutorials on it. Would someone please like to tell me how I could do this?

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Evertt evertt Joined 20 Oct 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.