Laravel Nova: Showing more details in a BelongsTo field
Is it possible to display more data on a BelongsTo field in Laravel nova? The answer is yes!
Imagine you have a User Nova resource. The User should appear by name in the index and detail views etc.
Now imagine you have another Nova resource, for example, a Post resource. You want to attach a User to this Post using a BelongsTo field. But only displaying the User.name in this specific view is just to limited. You want to display more fields in this specifc case, for example the User's email address and id. It's possible using a simple trick! Here's how to do it.

Step 1: Nothing tricky yet on the User resource
Just define a public static $title and set it to the name attribute. Your User resource will display by name in User indexes etc.
app/Nova/User.php
class User extends Resource
{
// ...
public static $title = 'name';
// ...
}
2
3
4
5
6
Step 2: You can extend Nova resources! 🎉
You can extend Nova resources! Simply extend your User resource created in step 1. You can call it whatever you like. I named mine UserDetailedTitle and placed in a Helpers folder because I want to keep my Nova resources folder clean.
Hide this resource from global Nova search, and navigation, because you don't want it to show up anywhere per default.
Now we can define a more descriptive title on this new resource.
app/Nova/Helpers/UserDetailedTitle.php
namespace App\Nova\Helpers;
use App\Nova\User;
class UserDetailedTitle extends User
{
// hide resource
public static $globallySearchable = false;
public static $displayInNavigation = false;
// how you want the resource to appear
public function title()
{
return implode(' / ', [
$this->id,
$this->name,
$this->email
]);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Step 3: Use this extended resource in your BelongsTo field
Set the third parameter to your extended Nova resource.
app/Nova/Post.php
namespace App\Nova;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\BelongsTo;
use App\Nova\Helpers\CustomerDetailedTitle;
class Post extends Resource
{
// ...
public function fields(Request $request)
{
return [
BelongsTo::make('Author', 'author', UserDetailedTitle::class)
->searchable(),
];
}
// ...
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
It's magic! 🎉