Search code examples
phpmysqllaraveleloquent-relationshiplaravel-backpack

How to display column value of a relationship with laravel backpack?


Cannot display another column from a relationship on Laravel 9 + Backpack

So, i have a table with invoices ... enter image description here

I have a table with clients ... enter image description here

I have defined in my Invoices model the following relationship

public function client_id()
    {
        return $this->belongsTo(Client::class, 'client_id', 'client_id');
    }

... and i have defined in my Clients model the following relationship

    public function invoice() {
        return $this->hasMany(Invoice::class, 'client_id');
    }

My problem is that I cannot seem to find how I can display the company name for the company that the invoice has been issued.

enter image description here

I have looked into the documentation https://backpackforlaravel.com/docs/5.x/crud-columns#relationship-pro but i cannot seem to make it work.

 CRUD::addColumn([
        // any type of relationship
        'name'         => 'client_id', // name of relationship method in the model
        'type'         => 'relationship',
        'label'        => 'Client name', // Table column heading
        // OPTIONAL
        'entity'    => 'client_id', // the method that defines the relationship in your Model
        'attribute' => 'client_company', // foreign key attribute that is shown to user
        'model'     => \App\Models\Client::class, // foreign key model
    ]);

I'm guessing i'm doing something wrong. Any chance I could have a snippet?

Thank you, George


Solution

  • First, it should be:

    public function client()
    {
       return $this->belongsTo(Client::class, 'client_id', 'client_id');
    }
    

    Second:

    CRUD::addColumn([
            // any type of relationship
            'name'         => 'client', // name of relationship method in the model
            'type'         => 'relationship',
            'label'        => 'Client name', // Table column heading
        ]);