Search code examples
laravellaravel-nova

Translation of BelongsTo in Laravel Nova


I use for translations fields in Nova

Text::make(__('Name User'), 'name')

But I don't understand the manual to make the title of the BelongsTo fields translatable

Title Attributes When a BelongsTo field is shown on a resource creation / update screen, a drop-down selection menu or search menu will display the "title" of the resource. For example, a User resource may use the name attribute as its title. Then, when the resource is shown in a BelongsTo selection menu, that attribute will be displayed:

Well... On my code, this fails because translations produces in name of model, not in Label of relation Ship.

BelongsTo::make(__('User'), 'users')->withMeta([
  'belongsToId' =>  $this->user_id ?? auth()->user()->id
])->hideFromDetail()
local.ERROR: Class 'App\Nova\Usuario' not found {"userId":1,"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Class 'App\\Nova\\Usuario' not found at /home/abkrim/Sites/albaridnova/vendor/laravel/nova/src/Fields/BelongsTo.php:118)

Code on Nova\User

public static $model = 'App\\User';

public static $title = 'email';

public static $search = ['id', 'name', 'email'];

public static function availableForNavigation(Request $request)
{
    return $request->user()->isAdmin();
}

public static function label()
{
    return __('Users');
}

public static function singularLabel()
{
    return __('User');
}

When show User resource not problem. Labels translations are done.

But if go to resource Mailbox, field BelongsTo not show translations


Solution

  • This happens because if you don't specify the third argument (resource) on the make method, Nova will think that your resource is called in the same way as the Label (eg: label: User then resourceName: User) and will try to search for that resource class.

    Obviously you can override that by passing the resource class as third argument:

    // Add the import of your resource if its class
    // is not in the same directory as this file
    BelongsTo::make(__('User'), 'users', User::class)->withMeta([
      'belongsToId' =>  $this->user_id ?? auth()->user()->id
    ])->hideFromDetail(),