Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 325
Vineeth Vijayan Avatar asked Dec 08 '22 13:12

Vineeth Vijayan


1 Answers

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)
like image 97
Mozammil Avatar answered Mar 30 '23 00:03

Mozammil