Juliatzin
Juliatzin

Reputation: 19725

Laravel nova and belongsToThrough?

Is there a way to display in Laravel Nova Resource a relation like this ?

$report->meter->user

where

- a report belongs to a meter
- a meter belongs to a user

I am in report ressource and I want to display related user

Upvotes: 3

Views: 1570

Answers (1)

Matt
Matt

Reputation: 843

I struggled with this lately. What we seek is a BelongsToThrough relationship field. That type of relationship isn't natively supported by Laravel, which means there's no field for it in Nova either. However, you can easily implement it in Laravel by installing this package: https://github.com/staudenmeir/belongs-to-through

You can then add your report relationship to the User model.

// App\Models\Report
use \Znck\Eloquent\Traits\BelongsToThrough;

public function report()
{
    return $this->belongsToThrough('App\Models\User','App\Models\Meter');
}

And you can use a regular BelongsTo relationship within Nova.

// App\Nova\Report

public function fields(Request $request)
{
    return [
        BelongsTo::make('User')
    ]
}

Note: This would work for the Report index/details views, but you'll want to exclude it from the edit form. (Consider a computed Text field, if you want to display the user on the edit form.)

Upvotes: 4

Related Questions