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

zrosen's avatar

Parent/child relationship by ID within the same table

Hi all,

I am trying to build a relationship for my model, Client. A Client can have a subclient (children) or it can be a child of another client (parent). Or, it can be by itself as just a client.

I have the Client model with columns id and name, and the ClientRelationship model with the columns client_id and parent_id.

ClientRelationship migration:

$table->unsignedBigInteger('client_id');
$table->unsignedBigInteger('parent_id');
$table->foreign('client_id')->references('id')->on('clients');
$table->foreign('parent_id')->references('id')->on('clients');

And within the Client model:

public function parent()
{
return $this->hasOne(ClientRelationship::class);
}

public function children()
{
return $this->hasMany(ClientRelationship::class);
}

When I have this display on my blade template, parent is working and showing what it should be using:

@if ($client->parent)
   <li>{{ $client->parent->id }}</li>
@endif

However, children are not showing properly with:

@if ($client->children)
   @foreach ($client->children as $child)
      <li>{{ $child->id }}</li>
   @endforeach
@endif

Also, in a perfect would I'd have it displaying the client names, not IDs, but I wanted to first figure out why I can't get children to display properly.

Thanks for any advice, I feel like I must be missing something silly!

0 likes
5 replies
sr57's avatar

However, children are not showing properly with:

Can you share a set of data (extract dump sql) with results and expected results ?

jlrdw's avatar

Did you attach related data, using the with key word in controller before passing to view.

Also have you viewed some videos on relations.

MostafaGamal's avatar

I think you should pass the parent_id as a second argument in the parent relation since the default is client_id ... Also pass the the client_id as second argument in the children relation .... Finally as @jlrdw said make sure that you used with in you controller

awsqed's avatar

I think you don't need the extra client_id, because when a client has a parent, the parent also knows that it has a subclient. So a client can has many subclients, and be a child (belongs to) of another client.

UsmanBasharmal's avatar

Since a client may or may not have a parent, then parent_id should be nullable.

$table->unsignedBigInteger('parent_id')->nullable();

Then to get children of a client, you are looking for all clients who have parent_id equals to its client id id.

public function children()
{
    return $this->hasMany(ClientRelationship::class, 'parent_id');
}

You don't need client_id field, parent_id field should suffice.

Please or to participate in this conversation.