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

2875 views php
-1

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?

answered question

1 Answer

3

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)

posted this

Have an answer?

JD

Please login first before posting an answer.