Search code examples
laravellaravel-nova

Laravel Nova - Show the name of the resource in the ID field instead of the actual ID


Is it possible in Laravel Nova to show for example the first- and lastname in the ID field instead of the actual ID. But then I want still to be able to click on it to query the resource and open the view page of that resource. Laravel Nova does this in fact automatically when showing relationships in the index page. But I couldn't find a way to make the ID appear as the name of the resource.

My ID field is made like this:

    ID::make()->sortable(),

And my first- and lastname fields like this:

    Text::make('Firstname')
        ->sortable()
        ->rules('required', 'max:255'),
    Text::make('Lastname')
        ->sortable()
        ->rules('required', 'max:255'),

But if I write it like this:

    ID::make('Firstname')->sortable(),

It queries the model with the firstname instead of the ID. Anyone that can tell me how to solve this problem?


Solution

  • My solution is as follows:

    Create a TextField that combines the first- and lastname and returns a link that uses the ID of that entity.

      Text::make('Name', 'firstname', function () {
                    $url = \Nova::path()."/resources/{$this->uriKey()}/{$this->id}";
                    $name = $this->firstname.' '.$this->lastname;
    
                    return "<a class=\"no-underline dim text-primary font-bold\" href=\"{$url}\">{$name}</a>";
                })->asHtml()
                    ->sortable()
                    ->hideFromDetail()
                    ->hideWhenCreating()
                    ->hideWhenCreating(),
    

    This way it still can link to the detail page of that resource with the ID. To make this custom field sorttable I override the indexQuery function like this:

    public static $defaultSort = 'firstname';
    
    /**
     * Build an "index" query for the given resource.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function indexQuery(NovaRequest $request, $query)
    {
        if (static::$defaultSort && empty($request->get('orderBy'))) {
            $query->getQuery()->orders = [];
    
            return $query->orderBy(static::$defaultSort);
        }
    
        return $query;
    }
    

    The variable $defaultSort represents the column you want to be sorttable.