Skip to content

Instantly share code, notes, and snippets.

@AndreiTelteu
Last active February 26, 2024 09:37
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AndreiTelteu/c2a09fac30990ec042321963083ca3c4 to your computer and use it in GitHub Desktop.
Save AndreiTelteu/c2a09fac30990ec042321963083ca3c4 to your computer and use it in GitHub Desktop.
Custom bread field type stored in json format. For Laravel + Voyager admin panel

1. A new file: /app/Admin/FormFields/CustomFieldHandler.php

<?php
namespace App\Admin\FormFields;

use TCG\Voyager\FormFields\AbstractHandler;

class CustomFieldHandler extends AbstractHandler
{
    protected $codename = 'custom_field';
    public function createContent($row, $dataType, $dataTypeContent, $options)
    {
        return view('voyager::formfields.custom_field', [
            'row'             => $row,
            'options'         => $options,
            'dataType'        => $dataType,
            'dataTypeContent' => $dataTypeContent,
        ]);
    }
}

2. A new file: /resources/views/vendor/voyager/formfields/custom_field.blade.php

@php
$values = $dataTypeContent->{$row->field};
if (is_string($values)) { $values = json_decode($values, true); }
if (empty($values)) { $values = array(); }
@endphp
<div class="custom-field is-field-{{camel_case($row->field)}}">
    You can do anything here. Good luck !
    PS: Use $values to get te actual data, in form of an array.
</div>
@php $dataTypeContent->{$row->field} = $values; @endphp

3. Add in your app/Providers/AppServiceProvider.php

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;

use TCG\Voyager\Facades\Voyager as VoyagerFacade;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        /* ... */
        VoyagerFacade::addFormField("App\\Admin\\FormFields\\CustomFieldHandler");
    }
}

4. In every model that needs this custom field:

<?php
namespace App;
class User extends Model
{
    /* ... */
    protected $casts = [
        'custom_data' => 'array',
    ];
    public function setCustomDataAttribute($value)
    {
        if (is_string($value)) {
            $value = json_decode($value, true);
        }
        if (empty($value)) {
            $value = array();
        }
        $this->attributes['custom_data'] = json_encode($value);
    }
    
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment