Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Crm Toolkit Laravel Package

alexacrm/php-crm-toolkit

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require alexacrm/php-crm-toolkit
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Alexacrm\CrmToolkit\CrmToolkitServiceProvider::class,
    ],
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Alexacrm\CrmToolkit\CrmToolkitServiceProvider"
    

    Update .env with your Dynamics CRM credentials:

    CRM_URL=https://yourorg.crm.dynamics.com
    CRM_CLIENT_ID=your_client_id
    CRM_CLIENT_SECRET=your_client_secret
    
  3. First Use Case: Fetching Accounts

    use Alexacrm\CrmToolkit\Facades\CrmToolkit;
    
    $accounts = CrmToolkit::fetch('account', ['name' => 'Test Company']);
    dd($accounts);
    

Implementation Patterns

Core Workflows

  1. CRUD Operations

    • Create:
      $account = CrmToolkit::create('account', [
          'name' => 'New Company',
          'revenue' => 1000000
      ]);
      
    • Update:
      $account = CrmToolkit::update('account', $account->id, ['name' => 'Updated Name']);
      
    • Delete:
      CrmToolkit::delete('account', $account->id);
      
  2. Querying with OData Use OData syntax for filtering, sorting, and pagination:

    $contacts = CrmToolkit::fetch('contact', [
        '$select' => 'fullname,emailaddress1',
        '$filter' => "contains(fullname, 'John')",
        '$top' => 10
    ]);
    
  3. Relationships Fetch related entities (e.g., contacts for an account):

    $account = CrmToolkit::fetch('account', ['name' => 'Test'], [
        '$expand' => 'contact_customer'
    ]);
    
  4. Bulk Operations Use bulk() for batch operations (e.g., updating multiple records):

    $updates = [
        ['id' => 1, 'name' => 'Updated 1'],
        ['id' => 2, 'name' => 'Updated 2']
    ];
    CrmToolkit::bulk('account', 'update', $updates);
    

Integration Tips

  1. Laravel Eloquent Integration Create a custom Eloquent model for seamless ORM usage:

    namespace App\Models;
    
    use Alexacrm\CrmToolkit\Eloquent\CrmModel;
    
    class Account extends CrmModel
    {
        protected $entityName = 'account';
        protected $fillable = ['name', 'revenue'];
    }
    
    // Usage:
    $account = Account::where('name', 'Test')->first();
    
  2. Event Listeners Listen to CRM webhook events (e.g., record creation):

    use Alexacrm\CrmToolkit\Events\RecordCreated;
    
    Event::listen(RecordCreated::class, function ($event) {
        Log::info("New {$event->entity} created: {$event->data->name}");
    });
    
  3. Caching Responses Cache frequent queries to reduce API calls:

    $accounts = Cache::remember('accounts_all', now()->addHours(1), function () {
        return CrmToolkit::fetch('account');
    });
    
  4. Error Handling Wrap CRM calls in a try-catch block:

    try {
        $data = CrmToolkit::fetch('opportunity');
    } catch (\Alexacrm\CrmToolkit\Exceptions\CrmException $e) {
        Log::error("CRM Error: " . $e->getMessage());
        return response()->json(['error' => 'CRM unavailable'], 500);
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated API

    • The package was last updated in 2018. Dynamics CRM APIs have evolved since (e.g., OAuth 2.0 changes, Web API v9.x).
    • Workaround: Use the CrmToolkit::setApiVersion() method to target a specific API version (e.g., 9.1):
      CrmToolkit::setApiVersion('9.1');
      
  2. Authentication Issues

    • If using client credentials, ensure the app registration in Azure AD has the correct API permissions (user_impersonation).
    • Debug Tip: Enable verbose logging in config/crm-toolkit.php:
      'debug' => true,
      
  3. Large Data Sets

    • Fetching large datasets (e.g., >5000 records) may hit API limits. Use $top and $skip for pagination:
      $pageSize = 5000;
      $offset = 0;
      do {
          $data = CrmToolkit::fetch('account', ['$top' => $pageSize, '$skip' => $offset]);
          $offset += $pageSize;
      } while (!empty($data));
      
  4. Case Sensitivity

    • Dynamics CRM entity names and field names are case-sensitive in OData queries. Always use lowercase:
      // Correct:
      CrmToolkit::fetch('account', ['$select' => 'name,revenue']);
      
      // Incorrect (will fail):
      CrmToolkit::fetch('account', ['$select' => 'Name,Revenue']);
      

Debugging Tips

  1. Enable API Logging Add this to AppServiceProvider@boot():

    \Alexacrm\CrmToolkit\CrmToolkit::setLogger(function ($message) {
        Log::debug('[CRM] ' . $message);
    });
    
  2. Inspect Raw Responses Use CrmToolkit::getLastResponse() to debug raw API responses:

    $response = CrmToolkit::fetch('account');
    dd(\Alexacrm\CrmToolkit\CrmToolkit::getLastResponse());
    
  3. Common HTTP Errors

    • 401 Unauthorized: Invalid credentials or expired tokens. Regenerate the client secret.
    • 403 Forbidden: Insufficient permissions. Check Azure AD app roles.
    • 404 Not Found: Entity or field name mismatch. Verify with Dynamics CRM Metadata Browser.

Extension Points

  1. Custom Entities Extend the CrmToolkit class to support non-standard entities:

    namespace App\Extensions;
    
    use Alexacrm\CrmToolkit\CrmToolkit as BaseCrmToolkit;
    
    class CustomCrmToolkit extends BaseCrmToolkit
    {
        public function fetchCustomEntity($entity, array $params = [])
        {
            return $this->fetch("custom_{$entity}", $params);
        }
    }
    
  2. Plugin Hooks Override default behaviors (e.g., request transformation):

    CrmToolkit::setRequestTransformer(function ($request) {
        $request->headers->set('X-Custom-Header', 'value');
        return $request;
    });
    
  3. Webhook Handling Register a custom webhook listener for real-time updates:

    CrmToolkit::onWebhook('account', function ($payload) {
        // Process payload (e.g., trigger a queue job)
        AccountUpdated::dispatch($payload);
    });
    

Performance Quirks

  1. Batch Processing

    • For bulk operations, use CrmToolkit::bulk() instead of looping individual calls. Example:
      $bulkUpdates = [];
      foreach ($accounts as $account) {
          $bulkUpdates[] = [
              'id' => $account->id,
              'name' => 'Updated: ' . $account->name
          ];
      }
      CrmToolkit::bulk('account', 'update', $bulkUpdates);
      
  2. Avoid N+1 Queries When fetching related entities, use $expand sparingly. Prefer eager loading in custom models:

    class Account extends CrmModel
    {
        public function contacts()
        {
            return $this->hasMany(Contact::class, 'customerid', 'id');
        }
    }
    // Usage:
    $account = Account::with('contacts')->find($id);
    
  3. Rate Limiting Dynamics CRM enforces 10 requests per second by default. Implement exponential backoff:

    use Symfony\Component\RateLimiter\RateLimiter;
    
    $limiter = new RateLimiter(10, 1);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver