Skip to content

Contacts

Contacts is one of the fundamental add-ons upon which other add-ons are built, and you can add your items to it.

Installation

bash
composer require obelaw/contacts
php artisan twist:setup
php artisan twist:migrate

How to use

Defining Contact Types

You can define and register new contact types according to your business needs. To do this, add the following code within the register method of any ServiceProvider class in your application:

php
use Obelaw\Contacts\ContactType;

ContactType::add('CUSTOMER', 1);
ContactType::add('VENDOR', 2);

// Retrieve a contact type by its key
ContactType::get('CUSTOMER');

In this example, we've defined two contact types: 'CUSTOMER' with an ID of 1 and 'VENDOR' with an ID of 2. You can then retrieve these types using the ContactType::get() method.

Creating Contact Models

If you need to create specific contact models, such as a Customer or Vendor model, you can extend the base Contact model provided by the add-on. Here's an example:

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Obelaw\Contacts\Facades\ContactType;
use Obelaw\Contacts\Models\Contact;

class Customer extends Contact
{
    use HasFactory;

    /**
     * The "booted" method of the model.
     */
    protected static function booted(): void
    {
        static::addGlobalScope('customer', function (Builder $builder) {
            $builder->where('document_type', ContactType::get('CUSTOMER'));
        });

        static::creating(function (Model $model) {
            $model->document_type = ContactType::get('CUSTOMER');
        });
    }
}

In this Customer model:

  • We use a global scope named customer to automatically filter contacts where the document_type matches the CUSTOMER contact type.
  • In the creating event, we automatically set the document_type to CUSTOMER when a new Customer model is created.

You can then use this Customer model in your application just like any other Eloquent model to interact with customer contacts.