3

I have a database model with json column type called attributes. This column will contain additional details of the model.

For example: attributes : {'desc' : 'test', 'width' : '500'}.

I would like to display individual attribute (desc & width) in attributes column as a html field in Laravel admin resource.

I checked supported field types and doesn't seem supports.

Any suggestions how I can do this?

Saumini Navaratnam
  • 8,439
  • 3
  • 42
  • 70

4 Answers4

11

Here's how I was able to accomplish this in Nova 2.0. In my case I have a JSON column called fields. In the model, fields is cast to an array.

protected $casts = [
    'fields' => 'array'
];

Then in the resource, the column is mapped using the -> operator.

Text::make('Name', 'fields->name')
Brad Goliber
  • 111
  • 1
  • 2
4

I'm not sure if it's the recommended answer but i've found a way that should work for you.

Use an Eloquent Mutator: Eloquent Mutators

Then you define a getDescAttribute and a setDescAttribute and pass it in nova like a property on the model like so:

Text::make('Desc', 'desc')

Hope this helps.

Gianluca
  • 531
  • 4
  • 7
  • Well the problem comes when the "desc" and "width" are dynamic attributes and you don't know the whole list of those attributes. Any ideas ? – ArmeniaH Dec 04 '18 at 01:50
  • @ArmeniaH you could get the array from ->fields, iterate over the keys, and add fields as needed in the edit context. This would be a mess in the index view as each row could have different keys in the array. – benjaminhull Sep 27 '21 at 11:39
0

For example the value for 'desc' column is something like :

"{attributes : {'desc' : 'test', 'width' : '500'}}"

You can directly put it in table format :

KeyValue::make('Desc', 'desc**.attributes**')

Hope this helps

slfan
  • 8,950
  • 115
  • 65
  • 78
Jerry Chee
  • 11
  • 4
0

There is a package that allows you to achieve what you want to without any unnecessary changes to the behaviour of your model.

https://github.com/64robots/nova-fields

This would allow you to define each key of JSON array as actual fields that can be modified.

prog_24
  • 771
  • 1
  • 12
  • 26