maelstrom-cms / toolkit

A CMS Toolkit built on Laravel and React
https://www.maelstrom-cms.com
61 stars 6 forks source link

[Question] Customising data presented on index table #13

Closed porl closed 4 years ago

porl commented 4 years ago

Hi there. Is there an easy way to show a related column's data in the index table? By this I mean that I have the following model (simplified):

menu_item.id, menu_item.name, menu_item.parent_id

In my index I can easily show the three above columns, but I would like (just for the output in the maelstrom::layouts.index table view) to show the menu_item.name associated with the parent_id. so basically showing:

menu_item.id, menu_item.name, menu_item.parent_id->name (note that I'm not meaning -> in the php sense, just as a relationship)

Is there a way to use the $this->panel->index('admin.menu_items') functionality, or do I have to build something completely separate in order to get it to show the columns?

OwenMelbz commented 4 years ago

Hi, yeah this is all doable from Laravel itself

You can use Laravels eager loading system on the relationship

https://www.maelstrom-cms.com/advance/relationships.html

Then set up a column using dot notation. Eg menu_item.name

Or you can use Laravels accessor system to make a virtual attribute on your model eg getMenuNameAtrribute which returns the value you want to display

https://www.maelstrom-cms.com/advance/entry-transformer.html#appending-attributes

And then access the attribute name as any other column.

porl commented 4 years ago

Thank you!

I was trying variations of the first method and couldn't get it to work (still not sure why), however the second method worked a treat.

For reference, my attribute code was:

    public function getParentNameAttribute()
    {
        return NavMenu::where('id', '=', $this->parent_id)->pluck('name');
    }

(NavMenu was the actual name of my model of course).

Thanks for the quick response.