develpr
develpr

Reputation: 1406

How to use relationship data outside of relationship field in Laravel Nova?

I am trying to figure out how to do something seemingly simple with Laravel Nova, but I can't figure this out.

What I want to do is reference relationship data in a text field. I see in Nova, and understand how to reference a relationship via the HasOne, HasMany ... facades. But what I want to do is get relationship data like this:

Text::make('State', $this->state->name) 

This doesn't work, and something I noticed when trying to debug is that each function in a Nova resource seems to run multiple times. Here is the logging I added:

public function fields(Request $request) {
    logger($this->state->name)
}

When I do this, there are 3 logging instances, the first 2 containing the state name, and the third not. I think that may have something to do with it not working, but don't know what might be causing this.

Thank you in advance for help!

Upvotes: 2

Views: 3489

Answers (1)

udog
udog

Reputation: 1536

There's a simple way to get relationship data into a Nova Text field, just use a closure:

Text::make('State', function() { return $this->state->name; })

As for the multiple calls to the fields function, the answer has to do with the question: Do you have another Resource in your Nova folder that is related to the Resource we are discussing? If so, that is why -- it needs to call fields to display it properly. You can examine the following query string parameters to get more insight: viaResource, viaResourceId, and viaRelationship.

Upvotes: 2

Related Questions