Show Relation Field on Resource Index Hello,
I am using Laravel Nova.
is it possible to show a relation field on the index of I resource? I searched the documentation but can not find anything like that.
For example:
A user has a role and I want to display that role not only in the details view but also directly on the index.
The User and the Role are two tables with a HasMany relation.
Any idea?
No idea what you mean with not only in the details view but also directly on the index. if you talking about showing it on the indes.blade.php then you surely can.
If you have a relationship in User called roles(), then in your index blade, you just need to do the following:
@foreach($users as $user)
{{ $user->roles }}
@endforeach
You’ll probably want to foreach through roles too to get $role->name
Oh, sorry I guys. I am talkin about Laravel Nova.
It seems that the "BelongsToMany" relationships are limited in how they get displayed. I've only been able to get them to show on the View Page. I can't get them to show on the Index or Edit pages
You can pass a closure to the Text class to return whatever value you need.
Example:
Text::make('Roles', function () {
return $this->roles->first()->name;
})
->onlyOnIndex(),
@flipjms it gives me 'Object of class Closure could not be converted to a String'. Any idea why is that and how to fix it. I read the Nova doc too but its not working
@FLIPJMS - exactly what I was looking for, thanks
The downside is that is not sortable :(
This works for me with (multiple) hasOne objects
Text::make('Roles', 'roles->column_name')
@DanNeon it's work. thanks. everyone should try it
You can also create a computed field, as example for a HasOne relationship that doesn't appear in the index view:
Text::make('Name', function () {
$name = $this->user->name;
$userId = $this->user->id;
$userResourceUriKey = User::uriKey();
$url = "/nova/resources/{$userResourceUriKey}/{$userId}";
return "<a class=\"link-default\" href='{$url}'>{$name}</a>";
})->asHtml()
->canSee(function ($request) {
return $request->user()->can('view', $this->user);
}),
Please sign in or create an account to participate in this conversation.