Laravel Nova BelongsTo not working when relationship method name and foreign key prefix are different

Belongs to relationship not working in my Nova application when relationship method name and foreign key prefix are different.

I have two tables, event & client_location with Models Event & ClientLocation

Event Model:

class Event extends Model
{
   public function clientLocation()
   {
       return $this->belongsTo(\App\ClientLocation::class, 'location_id');
   }
}

ClientLocation Model:

class ClientLocation extends Model
{
   public function events()
   {
       return $this->hasMany(\App\Event::class, 'location_id');
   }
}

Nova Resource fields method for Event:

public function fields(Request $request)
{
    return [
        ID::make()->sortable(),
        BelongsTo::make('clientLocation'),
    ];
}

Any idea on how to handle this issue?

1 answer

  • answered 2018-11-08 06:54 Mozammil

    BelongsTo::make() can take 3 arguments.

    They are:

    1. Name to display
    2. Name of the relationship
    3. Nova resource

    In your particular case, this should work

    BelongsTo('Events', 'clientLocation', App\Nova\ClientLocation::class)