Search code examples
phplaravelvoyager

Laravel Voyager Custom relationship attributes not working


I am using Laravel v:9.52.16 on PHP 8.1.0

According to the documentation of Laravel Voyager Custom relationship attributes:

Suppose I have a PlatformCategory Model and its related table in the database contains f_name and l_name columns. I need to show the full name on the related models inside the Voyager admin panel dashboard of the PlatformCategory by using custom relationship attributes.

I've tried the following:

public $additional_attributes   = ['full_name'];
public function getFullNameReadAttribute()
{
    return "{$this->f_name} {$this->_name}";
}

image of how related with the voyager bread However, this results in the following error:

QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'full_name' in 'field list'
SELECT `full_name`, `id` FROM `platform_categories` WHERE 0 = 1 AND `platform_categories`.`deleted_at` IS NULL
The error message indicates that the database query is attempting to select a column called full_name, but it doesn't exist in the platform_categories table.

How can I fix this issue and display the full name of the PlatformCategory model in the Voyager admin panel?


Solution

  • the solution was to edit this file:

    tcg\voyager\resources\views\formfeilds\relationship.blade.php:
    

    inside this block of code:

     @php
                            $selected_keys = [];
    
                            if (!is_null($dataTypeContent->getKey())) {
                                $selected_keys = $dataTypeContent->belongsToMany(
                                    $options->model,
                                    $options->pivot_table,
                                    $options->foreign_pivot_key ?? null,
                                    $options->related_pivot_key ?? null,
                                    $options->parent_key ?? null,
                                    $options->key
                                )->pluck($options->table.'.'.$options->key);
                            }
                            $selected_keys = old($relationshipField, $selected_keys);
                            $selected_values = app($options->model)->whereIn($options->key, $selected_keys)->pluck($options->label, $options->key);
                        @endphp
    

    we need to change the

    $selected_values = app($options->model)->whereIn($options->key, $selected_keys)->pluck($options->label, $options->key);
    

    to :

    $selected_values = app($options->model)->whereIn($options->key, $selected_keys)->get()->pluck($options->label, $options->key);