laravel / nova-issues

553 stars 34 forks source link

[Bug] setting uriKey to existing resource's uriKey causes fields to be overridden #3058

Closed vesper8 closed 3 years ago

vesper8 commented 3 years ago

I have a User resource that has a nested resource which is also users (think parent / children)

On my "Parent" user resource I have lots of fields

Then I have a HasMany like this:

HasMany::make(__('Children'), 'Children', UserChild::class),

This correctly lists the parent's children as a nested resource.

However I want it so that when clicking the view icon or clicking on the id, it should open up the main "users" resource, because children can be parents too and have children of their own

I achieve this by changing the uriKey

class UserChild extends Resource
{
    public static $model = \App\User::class;

    public static function uriKey()
    {
        return 'users';
    }

    public function fields(Request $request)
    {
        return [
            ID::make('ID', 'id')->sortable(),

            Text::make('Name')
                ->sortable()
                ->rules('required', 'max:255'),
        ];
    }
...

The problem (bug) is that when I change the uriKey to users it does not let me specify fields for my UserChild resource and instead it automatically uses the fields from my User resource ?? (I am not extending my User resource so this happens quite magically and unexpectedly)

My User resource has 20+ fields, my UserChild resource only has 2 fields because I only want to display a summary of the user when displaying them as a nested resource inside my User resource

Why does uriKey behave this way? Seems like a bug to me

crynobone commented 3 years ago

Why does uriKey behave this way? Seems like a bug to me

uriKey() is the unique identifier for a resource. So when you reuse the resource uriKey more than one it would lead to unexpected behavior, and above is a good example where this would failed.

Please use unique uriKey() for every resource.

vesper8 commented 3 years ago

@crynobone how then can I change the url of the view icon / ID link ?

I want my "sub-users" to open as a "user" resource when you click the view icon or ID link

vesper8 commented 3 years ago

I found an acceptable workaround

First I hide the view icon by using this:

public function authorizedToView(Request $request)
{
    return false;
}

And then replacing the ID field with a custom Text field like this:

Text::make('ID', function ($model) {
    return "<a class='whitespace-no-wrap no-underline dim text-primary font-bold' href='/nova/resources/users/{$model->id}'>{$model->id}</a>";
})->asHtml(),

Wish there was a way to override the default linking on the view icon / id fields however.. Now I miss my view icon and I miss my sortable ID field