Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alexcool68's avatar

It's working but I don't understand why

Hello everybody,

I have to say that my code is working fine but I don't understand why ... I want to add some custom fields for different "modules".

for exemple I have 3 tables : Cameras, Servers and custom_fields.

Camera & Server model :

public function custom_fields()
{
    return $this->morphToMany('App\Models\Camera', 'item', 'description_fields', '', 'name')
        ->withPivot('name', 'value')
        ->withTimestamps();
}

The table for this relation :

    Schema::create('description_fields', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('item_id')->unsigned();
        $table->string('item_type');
        $table->string('name');
        $table->string('value');
        $table->timestamps();
    });

I can add some elements via this line in the controller :

$camera->custom_fields()->attach($request->custom_field);

My question is about the model, why I have write :

morphToMany('App\Models\Camera', 'item', 'description_fields', '', 'name')

I don't understand why I have to specify the 2 last parameters: '', 'name' (change 'name' by 'value' and it's working, but if I delete '','name' it doesn't work).

I have read the doc for the params but I still don't understand (I'm not a profesional developper but I learn by myself). If anyone can take 5 minutes to explain me, it will be appreciated.

Thanks in advance.

Alex.

0 likes
1 reply
alexcool68's avatar
alexcool68
OP
Best Answer
Level 1

I had rewrite my relation by this one :

return $this->morphToMany('App\Models\Server', 'item', 'description_fields', '', 'item_id')->withPivot('name', 'value')->withTimestamps();

It working fine now but I have to use {{ $custom_field->pivot->name }} in blade. It's okay I get it !

Please or to participate in this conversation.