PHP code example of plin-code / laravel-custom-fields

1. Go to this page and download the library: Download plin-code/laravel-custom-fields library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

plin-code / laravel-custom-fields example snippets


use PlinCode\CustomFields\Facades\CustomFields;

$fieldModel = CustomFields::fieldModel();
$valueModel = CustomFields::valueModel();



declare(strict_types=1);

namespace App\Providers;

use App\Models\Patient;
use Illuminate\Support\ServiceProvider;
use PlinCode\CustomFields\Facades\CustomFields;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        CustomFields::registerEntity(Patient::class, 'patient', 'Patient');
    }
}



declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use PlinCode\CustomFields\Concerns\HasCustomFields;

class Patient extends Model
{
    use HasCustomFields;
}

use App\Models\Patient;
use PlinCode\CustomFields\Facades\CustomFields;
use PlinCode\CustomFields\Models\CustomField;

$patientKey = CustomFields::entityKey(Patient::class); // 'patient'

$riskLevel = CustomField::create([
    'entity_type' => $patientKey,
    'name' => '  Risk level  ',
    'type' => 'select',
    'is_level'

CustomField::create([
    'entity_type' => $patientKey,
    'name' => 'Date of birth',
    'type' => 'date',
]);

CustomField::create([
    'entity_type' => $patientKey,
    'name' => 'Allergies',
    'type' => 'multiselect',
    'options' => [
        ['key' => 'pollen', 'label' => 'Pollen', 'is_active' => true],
        ['key' => 'latex', 'label' => 'Latex', 'is_active' => true],
    ],
]);

CustomField::create([
    'entity_type' => $patientKey,
    'name' => 'Notes',
    'type' => 'textarea',
]);

$patient->setCustomFields([
    'risk-level' => 'high',
    'date-of-birth' => '1985-03-02',
    'allergies' => ['pollen', 'latex'],
]);

$patient->getCustomFields();
// [
//     'risk-level' => 'high',
//     'date-of-birth' => '1985-03-02',
//     'allergies' => ['pollen', 'latex'],
//     'notes' => null,
// ]

$patient->getCustomField('risk-level'); // 'high'
$patient->setCustomField('notes', 'Follow up in June.');
$patient->clearCustomField('notes');

$patient->setCustomField('date-of-birth', null); // the row is deleted
$patient->getCustomField('date-of-birth');       // null

$patient->clearCustomField('date-of-birth');     // the same thing, explicitly

$patient->setCustomField('allergies', []);   // row kept, reads back as []
$patient->setCustomField('allergies', null); // row deleted, reads back as []

$patient->setCustomFields(['notes' => 'Follow up.']);                     // partial
$patient->setCustomFields(['notes' => 'Follow up.'], complete: true);     // complete

use PlinCode\CustomFields\Facades\CustomFields;

CustomFields::validate($patient, $request->input('custom_fields', []), complete: true);

$rules = CustomFields::validator()->rules(Patient::class, complete: true);
// ['risk-level' => ['

use Illuminate\Validation\ValidationException;

try {
    $patient->setCustomFields($request->input('custom_fields', []));
} catch (ValidationException $e) {
    $e->errors(); // ['risk-level' => ['The selected option legacy is invalid for risk level.']]
}

$riskLevel->updateOptions([
    ['key' => 'low', 'label' => 'Low risk', 'is_active' => true],
    ['key' => 'high', 'label' => 'High risk', 'is_active' => true],
    ['key' => 'legacy', 'label' => 'Legacy', 'is_active' => false],
    ['key' => 'critical', 'label' => 'Critical', 'is_active' => true],
]);

$riskLevel->optionsForInput(); // the active options, ready for a form
$riskLevel->activeOptionKeys(); // ['low', 'high', 'critical']
$riskLevel->optionKeys();       // ['low', 'high', 'legacy', 'critical']

use App\Models\Patient;
use PlinCode\CustomFields\Facades\CustomFields;
use Spatie\QueryBuilder\QueryBuilder;

public function index()
{
    $options = CustomFields::queryOptionsFor(Patient::class);

    return QueryBuilder::for(Patient::class)
        ->allowedFilters(...$options['filters'])
        ->allowedSorts(...$options['sorts'])
        ->paginate();
}

Patient::whereCustomField('risk-level', 'high')->get();

use App\Models\Patient;
use PlinCode\CustomFields\Facades\CustomFields;
use Spatie\QueryBuilder\QueryBuilder;

$patients = QueryBuilder::for(Patient::class)
    ->allowedFilters(...CustomFields::filtersFor(Patient::class))
    ->allowedSorts(...CustomFields::sortsFor(Patient::class))
    ->paginate();

$options = CustomFields::queryOptionsFor(Patient::class);

$patients = QueryBuilder::for(Patient::class)
    ->allowedFilters(...$options['filters'])
    ->allowedSorts(...$options['sorts'])
    ->paginate();

CustomFields::keyPrefix();                       // 'cf_'
CustomFields::filterName('risk-level');          // 'cf_risk-level'
CustomFields::filterName('risk-level', 'in');    // 'cf_risk-level:in'
CustomFields::sortName('date-of-birth');         // 'cf_date-of-birth'

use App\Models\Patient;
use PlinCode\CustomFields\Facades\CustomFields;
use PlinCode\EloquentSorts\Sorts\RelationSorter;
use Spatie\QueryBuilder\AllowedSort;
use Spatie\QueryBuilder\QueryBuilder;

$options = CustomFields::queryOptionsFor(Patient::class);

$patients = QueryBuilder::for(Patient::class)
    ->allowedFilters(...$options['filters'])
    ->allowedSorts(
        AllowedSort::field('last_name'),
        AllowedSort::custom('clinic', new RelationSorter('clinics', 'clinic_id')),
        ...$options['sorts'],
    )
    ->paginate();

use PlinCode\CustomFields\Facades\CustomFields;

foreach (CustomFields::types() as $key => $type) {
    $choice = [
        'value' => $key,                 // 'select'
        'label' => $type->label(),       // 'Select'
        'input' => $type->inputHint(),   // 'select'
    ];
}

use App\Models\Patient;
use PlinCode\CustomFields\Facades\CustomFields;

$fieldModel = CustomFields::fieldModel();

$definitions = $fieldModel::query()
    ->where('entity_type', CustomFields::entityKey(Patient::class))
    ->where('is_active', true)
    ->orderBy('sort_order')
    ->get();

$values = $patient->getCustomFields();

$form = $definitions->map(fn ($field) => [
    'name' => $field->slug,                          // 'risk-level'
    'label' => $field->name,                         // 'risk level'
    '



declare(strict_types=1);

namespace App\CustomFields;

use Illuminate\Database\Eloquent\Model;
use PlinCode\CustomFields\Types\TextType;

class CountryType extends TextType
{
    public static function key(): string
    {
        return 'country';
    }

    public function rules(Model $field): array
    {
        return ['nullable', 'string', 'size:2'];
    }

    public function label(): string
    {
        return 'Country';
    }

    public function queryOperations(): array
    {
        return ['equals', 'in', 'is_null', 'is_not_null', 'sort'];
    }
}

CustomFields::registerType(CountryType::class);
bash
php artisan vendor:publish --tag="laravel-custom-fields"
bash
php artisan vendor:publish --tag="laravel-custom-fields-config"
bash
php artisan vendor:publish --tag="laravel-custom-fields-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="laravel-custom-fields-lang"