PHP code example of byrcsc / laravel-custom-fields

1. Go to this page and download the library: Download byrcsc/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/ */

    

byrcsc / laravel-custom-fields example snippets


use ByRcsc\LaravelCustomFields\Concerns\HasCustomFields;
use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    use HasCustomFields;
}

use ByRcsc\LaravelCustomFields\Enums\FieldType;
use ByRcsc\LaravelCustomFields\Facades\CustomFields;

CustomFields::define(Customer::class, [
    'key' => 'account_tier',
    'type' => FieldType::Select,
    'options' => ['standard', 'premium'],
    'label' => 'Account tier',
    'default' => 'standard',
    'rules' => ['

$customer = Customer::query()->findOrFail(1);

$customer->setCustomField('account_tier', 'premium');

$customer->getCustomField('account_tier');   // 'premium'
$customer->customFields;                     // Collection: ['account_tier' => 'premium']

Customer::query()->whereCustomField('account_tier', 'premium')->get();

use ByRcsc\LaravelCustomFields\Contracts\TenantResolver;

final class SubdomainTenantResolver implements TenantResolver
{
    public function currentTenant(): ?string
    {
        return request()->route('tenant');
    }
}

$article->setCustomField('priority', 'high');
$article->setCustomFields(['priority' => 'high', 'reading_minutes' => 9]);

$article->getCustomField('priority');
$article->customFields;   // every visible field, keyed by key

final class StoreArticleRequest extends FormRequest
{
    public function rules(): array
    {
        return CustomFields::rulesFor(Article::class, prefix: 'custom_fields');
    }

    public function attributes(): array
    {
        return CustomFields::attributeNamesFor(
            Article::class,
            prefix: 'custom_fields',
        );
    }
}

'rules' => ['

Article::query()->whereCustomField('priority', 'high');
Article::query()->whereCustomFieldIn('priority', ['low', 'high']);

Article::query()->whereCustomField('tags', 'news');

Article::query()->with('customFieldValues')->get();

use ByRcsc\LaravelCustomFields\Models\CustomFieldValue;

CustomFieldValue::saved(function (CustomFieldValue $value): void {
    // reindex the record this value belongs to
});
bash
php artisan vendor:publish --tag=custom-fields-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=custom-fields-config