Benjacho / belongs-to-many-field-nova

Belongs To Many field Laravel nova to represent many to many relationship in field.
MIT License
157 stars 80 forks source link

Showing wrong title #114

Closed levidurfee closed 2 years ago

levidurfee commented 2 years ago

I have three Resources:

  1. Location
  2. Post
  3. Group

A Post can have multiple Location's. Some locations have the same name but belong to a different Group.

To indicate which Group a Location belongs to, we change the title to include the Group name. This works fine at first. The dropdown shows all of the Location's with their Group's names in parenthesis.

After we save a Post with a Location selected, the details page doesn't show the title we created for our Location resource. If we edit the Post, the selected Location does not show the correct title either. It only shows the name field.

I also tried creating an accessor on the Location Model (public function getTitleAttribute()), but I had similar issues.

<?php
// app/Models/Post.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function locations()
    {
    return $this->belongsToMany(Location::class);
    }
}
<?php
// app/Nova/Location.php

namespace App\Nova;

class Location extends Resource
{
    public function title(): string
    {
        return "{$this->resource->name}  ({$this->resource->group->title})";
    }
}

<?php
// app/Nova/Post.php

namespace App\Nova;

use Benjacho\BelongsToManyField\BelongsToManyField;

class Post extends Resource
{
    public function fields(Request $request)
    {
        return [
        BelongsToManyField::make('Locations')->hideFromIndex(),
    ];
    }
}
levidurfee commented 2 years ago

Following #104 's workaround got this working.