An easy way for attaching contacts to Eloquent models in Laravel. Inspired by the following packages:
Require the package by running
composer require chuckcms/laravel-contacts
php artisan vendor:publish --provider="Chuckcms\Contacts\ContactsServiceProvider"
This command will publish a config/contacts.php
and a migration file.
You can modify the default fields and their rules by changing both of these files.
After publishing you can run the migrations
php artisan migrate
You can use the HasContacts
trait on any model.
<?php
namespace App\Models;
use Chuckcms\Contacts\Traits\HasContacts;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
use HasContacts;
// ...
}
After doing this you can use the following methods.
$company = Company::first();
$company->addContact([
'first_name' => 'John', // required
'last_name' => 'Doe', // defaults to: null
'mobile' => '+32.470123456', // defaults to: null
'email' => 'john.doe@email.com', // defaults to: null
'is_public' => true, // defaults to: false
'is_primary' => true, // defaults to: false
]);
use Chuckcms\Contacts\Models\Contact;
$contact = Contact::first();
$company = Company::first();
$company->assignContact($contact);
$company = Company::first();
$contact = $company->getPrimaryContact();
$company->updateContact($contact, ['middle_name' => 'In The Middle']);
$company = Company::first();
$contact = $post->contacts()->first();
$company->removeContact($contact);
use Chuckcms\Contacts\Models\Contact;
$contacts = Contact::isPublic();
$company = Company::first();
$company->syncContacts($contacts);
// OR
$contacts = Contact::isPrimary()->pluck('id')->toArray();
$company->syncContacts($contacts);
// OR
$contact = Contact::isPrimary()->first();
$company->syncContacts($contact->id);
$company = Company::first();
$contact = $company->contacts()->first();
$company->deleteContact($contact);
$company = Company::first();
if ($company->hasContacts()) {
//do something
}
use Chuckcms\Contacts\Models\Contact;
$company = Company::find();
$contact = Contact::first();
if ($company->hasContact($contact)) {
//do something
}
//OR
if ($company->hasContact($contact->id)) {
//do something
}
//OR
$contacts = Contact::where('first_name', 'John')->get();
if ($company->hasContact($contacts)) {
//do something
}
//OR
$contacts = Contact::where('last_name', 'Doe')->pluck('id')->toArray();
if ($company->hasContact($contacts)) {
//do something
}
This will return true when one of the given contacts belongs to the model.
You can use the following methods to retrieve contacts and certain attributes.
$company = Company::first();
$publicContact = $company->getPublicContact();
$company = Company::first();
$primaryContact = $company->getPrimaryContact();
$company = Company::first();
$first_names = $company->getContactFirstNames();
Licensed under MIT license.
Written by Karel Brijs in Antwerp.