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

goatshark's avatar

Eloquent relationships, store() function

Scenario: I have three tables; nodes, modules, ports. The Node model hasMany modules and it hasMany ports. The Module model belongsTo Node and hasMany ports. The Port model belongsTo Node and belongsTo Port.

Logically, Node->Module->Port but I wanted to also be able to look up all ports in a node which is why the extra hasMany and belongsTo relationships. Maybe I'm not even making sense at this point....

When I try to create a port, I can almost get it done.

This:

public function store(CreatePortRequest $request, $node, $module)
    {
            $port = new Port($request->all());
            // Module::find($module->id)->ports()->save($port);
            Node::find($node->id)->ports()->save($port);
            return redirect()->route('nodes.modules.ports.index', ['node' => $node->id, 'module' => $module->id]);
    }

Gets me a new port but without a module_id.

This:

public function store(CreatePortRequest $request, $node, $module)
    {
            $port = new Port($request->all());
            Module::find($module->id)->ports()->save($port);
            // Node::find($node->id)->ports()->save($port);
            return redirect()->route('nodes.modules.ports.index', ['node' => $node->id, 'module' => $module->id]);
    }

Gets me a new port but without a node_id.

I am having trouble figuring out the syntax to create an entry in the ports table with both node_id and module_id.

Any thoughts would be sooooo appreciated. Thanks in advance!

0 likes
5 replies
JarekTkaczyk's avatar
Level 53

@goatshark First question - you've setup Node hasMany Port relation only to make it easy for you, is that right? Meaning, there is no real connection between the two?

If that's the case, then get rid of it, since you can easily achieve what you wanted:

// Node model
public function ports()
{
    return $this->hasManyThrough(Port::class, Module::class);
}

then you can get the ports of a node:

$node->ports; // collection of Port models related through Modules

So all you need to create a new one is:

public function store(CreatePortRequest $request, $node, $module)
{
            $port = new Port($request->all());
            $module->ports()->save($port);
            return redirect()->route('nodes.modules.ports.index', ['node' => $node->id, 'module' => $module->id]);
}

I assume you've bound $module to the route, so it is a Model already. That said, you don't need this part:

Module::find($module->id)...

because it has been already fetched for you.

1 like
goatshark's avatar

@JarekTkaczyk - Mind.Blown. Wow. Thank you so much. I read through the documentation on hasManyThrough and it looks like I can/should also remove the node_id column from my ports table. Is that correct?

Thank you!!!!

Please or to participate in this conversation.