Mauricio Etcheverry
Mauricio Etcheverry

Reputation: 46

Laravel Backpack: Show a Many to Many relationship in Show Operation

Couldn't find this in the docs.

Is there any standard way, without creating a custom widget, or overriding the view template, to show a Many to Many relationships in a CRUD's showOperation in Backpack for Laravel? If the answer is NO, what would be your approach to implement it?

Let's say I have a Course Model, and a User model, and there is a Many to Many between both

class Course extends Model
{
    public function students()
    {
        return $this->belongsToMany(User::class, 'course_students');
    }
}


class User extends Model
{
    public function courses()
    {
        return $this->belongsToMany(Course::class, 'course_students');
    }
}

In the Show Operation for the Course. How do I show a Table with all students?

Upvotes: 1

Views: 1544

Answers (1)

Wesley Smith
Wesley Smith

Reputation: 19571

Indeed, you can use the relationship column for this

Excerpt:

Output the related entries, no matter the relationship:

1-n relationships - outputs the name of its one connected entity;

n-n relationships - enumerates the names of all its connected entities;

Its name and definition is the same as for the relationship field type:

[  
   // any type of relationship
   'name'         => 'tags', // name of relationship method in the model
   'type'         => 'relationship',
   'label'        => 'Tags', // Table column heading
   // OPTIONAL
   // 'entity'    => 'tags', // the method that defines the relationship in your Model
   // 'attribute' => 'name', // foreign key attribute that is shown to user
   // 'model'     => App\Models\Category::class, // foreign key model
],

Backpack tries to guess which attribute to show for the related item. Something that the end-user will recognize as unique. If it's something common like "name" or "title" it will guess it. If not, you can manually specify the attribute inside the column definition, or you can add public $identifiableAttribute = 'column_name'; to your model, and Backpack will use that column as the one the user finds identifiable. It will use it here, and it will use it everywhere you haven't explicitly asked for a different attribute.

Upvotes: 2

Related Questions