PHPackages                             chandra-hemant/htkc-utils - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Mail &amp; Notifications](/categories/mail)
4. /
5. chandra-hemant/htkc-utils

ActiveLibrary[Mail &amp; Notifications](/categories/mail)

chandra-hemant/htkc-utils
=========================

Introducing a powerful and flexible dynamic search, push notifications, file upload, alpha numeric generator functions for Laravel applications, designed to simplify complex queries with nested and recursive relationship conditions. This package provides an elegant solution to dynamically search across multiple models and their related data, offering developers the ability to handle various levels of relationships in a single, streamlined query.

v1.2.7(1y ago)0228↓100%MITPHPPHP ^7.4 || ^8.0 || ^8.1 || ^8.2 || ^8.3

Since Sep 5Pushed 1y ago1 watchersCompare

[ Source](https://github.com/ChandraHemant/htkc-utils)[ Packagist](https://packagist.org/packages/chandra-hemant/htkc-utils)[ RSS](/packages/chandra-hemant-htkc-utils/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (2)Versions (7)Used By (0)

Dynamic Search Function for Laravel: Handle Nested Relationships and Complex Queries
====================================================================================

[](#dynamic-search-function-for-laravel-handle-nested-relationships-and-complex-queries)

Overview
--------

[](#overview)

Introducing a powerful and flexible dynamic search function for Laravel applications, designed to simplify complex queries with nested and recursive relationship conditions. This package provides an elegant solution to dynamically search across multiple models and their related data, offering developers the ability to handle various levels of relationships in a single, streamlined query.

Class Overview
--------------

[](#class-overview)

##### Namespace: ChandraHemant\\DynamicSearch

[](#namespace-chandrahemantdynamicsearch)

##### Namespace: ChandraHemant\\CommonUtils

[](#namespace-chandrahemantcommonutils)

##### Namespace: ChandraHemant\\FirebaseNotification

[](#namespace-chandrahemantfirebasenotification)

##### Author: Hemant Kumar Chandra

[](#author-hemant-kumar-chandra)

Features
--------

[](#features)

- Dynamic Model and Resource Handling: Pass the model name and resource class directly through the API request, enabling easy and dynamic querying across different models.
- Search Multiple Columns: Search across multiple columns within a model or its related models by simply specifying the columns in the API request.
- Nested and Recursive Relationships: The function supports nested relationships, allowing you to search deep within related models and their sub-relations.
- Flexible and Extendable: Easily extend or modify the functionality to fit your specific application's needs, making it a versatile tool for any Laravel project.
- Secure and Validated: Built-in validation ensures that only valid models and resources are processed, reducing the risk of errors and improving application security.

Usage Example
-------------

[](#usage-example)

Here's an example API request to demonstrate how the function works:

```
{
    "model": "Customer",
    "resource": "CustomerResource",
    "column": ["name", "phone", "email", "orders.product.category.name"],
    "value": "Electronics"
}
```

In this example, the function will:

- Search within the Customer model for matches in the name, phone, or email fields.
- Traverse the orders relationship to the product model, then further into the category model to search for matches in the name field.

Installation
------------

[](#installation)

You can easily add this functionality to your Laravel project by installing the package via Composer:

```
composer require chandra-hemant/htkc-utils
```

DynamicSearchHelper &amp; CommonUtils Class
===========================================

[](#dynamicsearchhelper--commonutils-class)

The `DynamicSearchHelper` &amp; `CommonUtils` class provides a set of methods for retrieving and manipulating data from a database table, especially tailored for use with Laravel's Eloquent ORM. This guide outlines how to effectively utilize these methods to implement dynamic search functionality.

Core Methods
------------

[](#core-methods)

### getCustomModelData

[](#getcustommodeldata)

Retrieves data from an Eloquent model with dynamic conditions and relationships.

```
public static function getCustomModelData(
    Model $eloquentModel,
    array $dynamicConditions = [],
    bool|string $isFirst = false,
    int $limit = 0
)
```

Parameters:

- `$eloquentModel`: Laravel Eloquent model instance
- `$dynamicConditions`: Array of query conditions
- `$isFirst`: Boolean/string to get first/last record
- `$limit`: Number of records to retrieve

Example usage:

```
$conditions = [
    [
        'method' => 'whereHas',
        'relation' => 'orders',
        'args' => ['status', '=', 'completed']
    ]
];
$result = CommonUtils::getCustomModelData($customerModel, $conditions);
```

### uploadFiles

[](#uploadfiles)

Handles file uploads with various configuration options.

```
public static function uploadFiles(
    Request $request,
    string $file,
    string $path,
    array $options = []
)
```

Parameters:

- `$request`: Laravel request instance
- `$file`: File input name
- `$path`: Upload path
- `$options`: Configuration array including:
    - `prefix`: File name prefix
    - `ref_file`: Reference to old file
    - `disk`: Storage disk
    - `default_extension`: Default file extension
    - `isArray`: Return array of paths
    - `isApi`: API mode flag

Example usage:

```
$options = [
    'prefix' => 'user_avatar',
    'disk' => 'public',
    'isArray' => false
];
$filePath = CommonUtils::uploadFiles($request, 'avatar', 'uploads/avatars', $options);
```

\*\*\* Note: Define the Disk in `config/filesystems.php`. It points to the `public/uploads` directory and is configured as a public disk. Make sure Disk name should be same as pointing directory name:

```
...

'uploads' => [
    'driver' => 'local',
    'root' => public_path('uploads'), // Files stored in public/uploads
    'url' => env('APP_URL') . '/uploads', // URL to access files
    'visibility' => 'public',
],

...
```

### alphaNumericGenerator

[](#alphanumericgenerator)

Generates alphanumeric sequences with customizable format.

```
public static function alphaNumericGenerator(
    int $num,
    string $const = '',
    string $prefix_id = '',
    string $ref_id = '',
    string $prefix_char = ''
): string
```

Parameters:

- `$num`: Number of digits
- `$const`: Constant prefix
- `$prefix_id`: Additional prefix
- `$ref_id`: Reference ID
- `$prefix_char`: Prefix character

Example usage:

```
$newId = CommonUtils::alphaNumericGenerator(
    4,
    'INV-',
    'Y22-',
    'INV-AA0001'
);
```

### dataSubmitRecursion

[](#datasubmitrecursion)

Recursively attempts to save model data with safety checks.

```
public static function dataSubmitRecursion(Model $model): bool
```

Example usage:

```
$saved = CommonUtils::dataSubmitRecursion($userModel);
```

### dataDeleteRecursion

[](#datadeleterecursion)

Recursively attempts to delete model data with safety checks.

```
public static function dataDeleteRecursion(Model $model): bool
```

Example usage:

```
$deleted = CommonUtils::dataDeleteRecursion($userModel);
```

### sendMail

[](#sendmail)

Sends emails with advanced configuration options.

```
public static function sendMail($recipient, $mailable, array $options = []): bool
```

Parameters:

- `$recipient`: Email recipient
- `$mailable`: Laravel Mailable class
- `$options`: Configuration array including:
    - `cc`: CC recipients
    - `bcc`: BCC recipients
    - `replyTo`: Reply-to address
    - `attachments`: Array of attachments

Example usage:

```
$options = [
    'cc' => ['admin@example.com'],
    'attachments' => [
        ['path' => 'invoices/latest.pdf', 'name' => 'Invoice.pdf']
    ]
];
$sent = CommonUtils::sendMail('user@example.com', new WelcomeMail(), $options);
```

### sendPushNotificationWithServerKey

[](#sendpushnotificationwithserverkey)

Handles send notification using firebase.

```
public static function sendPushNotificationWithServerKey(
    string $title,
    string $body,
    $fcm_token,
    array $config,
    array $additionalData = []
)
```

Parameters:

- `$title`: Notification title
- `$body`: Notification body
- `$fcm_token`: Single FCM token or an array of FCM tokens
- `$config`: Configuration options provided by the user:
    - `serverKey`: The FCM server key
    - `url`: The FCM endpoint URL (default: "")
    - `priority`: The priority of the notification (default: "high")
    - `android_channel_id`: The Android channel ID (default: "high\_importance\_channel")
- `$additionalData` Optional additional data to include in the payload

Example usage:

```
    $title = "Hello";
    $body = "This is a test notification.";
    $fcm_token = "YOUR_FCM_DEVICE_TOKEN";

    $config = [
        'serverKey' => 'YOUR_SERVER_KEY_HERE',
        'url' => 'https://fcm.googleapis.com/fcm/send',
        'priority' => 'high',
        'android_channel_id' => 'high_importance_channel',
    ];

    $additionalData = [
        'custom_key' => 'custom_value',
    ];

    $response = FirebaseNotification::sendPushNotificationWithServerKey($title, $body, $fcm_token, $config, $additionalData);

    if ($response['status']) {
        echo $response['message'];
    } else {
        echo "Error: " . $response['message'];
        print_r($response['response']);
    }
```

### sendPushNotification

[](#sendpushnotification)

Handles sending notifications using Firebase Cloud Messaging (FCM).

```
public static function sendPushNotification(
    string $title,
    string $body,
    $fcm_token,
    string $serviceAccountPath,
    array $config = [],
    array $additionalData = []
): array
```

#### Parameters:

[](#parameters)

- `$title`: Notification title.
- `$body`: Notification body.
- `$fcm_token`: Single FCM token or an array of FCM tokens.
- `$serviceAccountPath`: Path to the Firebase service account JSON file.
- `$config`: Configuration options provided by the user:
    - `url`: The FCM endpoint URL (default: `https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send`).
    - `android_channel_id`: The Android channel ID (default: `high_importance_channel`).
- `$additionalData`: Optional additional data to include in the payload (all values must be strings).

#### Example usage:

[](#example-usage)

```
use ChandraHemant/HtkcUtils/FirebaseNotification;

// Define your service account key path
$serviceAccountPath = __DIR__ . '/path/to/service-account-file.json';

// Set the FCM token (single or array of tokens)
$fcmToken = 'YOUR_FCM_DEVICE_TOKEN';

// Define the notification details
$title = 'New Alert';
$body = 'You have a new message!';
$additionalData = [
    'user_id' => '123',
    'notification_type' => 'alert',
];

// Configuration for the request
$config = [
    'url' => 'https://fcm.googleapis.com/v1/projects/your_project_id/messages:send',
    'android_channel_id' => 'high_importance_channel',
];

// Send the push notification
$response = FirebaseNotification::sendPushNotification(
    $title,
    $body,
    $fcmToken,
    $serviceAccountPath,
    $config,
    $additionalData
);

// Output the result
if ($response['status']) {
    echo 'Notification sent successfully: ' . json_encode($response['response'], JSON_PRETTY_PRINT);
} else {
    echo 'Failed to send notification: ' . $response['message'];
    if (isset($response['response'])) {
        echo 'Error details: ' . json_encode($response['response'], JSON_PRETTY_PRINT);
    }
}

//Other example with more config

$config = [
    'url' => 'https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send',
    'android_channel_id' => 'high_importance_channel',
    'priority' => 'PRIORITY_HIGH',
    'with_sound' => true,
    'notification_sound' => 'custom_sound',
    'android_icon' => 'ic_notification',
    'color' => '#FF0000',
    'led_color' => '#00FF00',
    'led_on_ms' => '500ms',
    'led_off_ms' => '500ms',
    'image_url' => 'https://example.com/image.jpg',
    'category_id' => 'message_category',
    'actions' => [
        [
            'id' => 'reply',
            'title' => 'Reply',
            'icon_path' => 'ic_reply'
        ],
        [
            'id' => 'dismiss',
            'title' => 'Dismiss',
            'icon_path' => 'ic_dismiss'
        ]
    ]
];

// Send notification
$result = FirebaseNotification::sendPushNotification(
    'Title',
    'Body',
    'FCM_TOKEN',
    'path/to/service-account.json',
    $config,
    ['custom_data' => 'value']
);
```

#### Expected Output:

[](#expected-output)

On success:

```
Notification sent successfully: {
    "name": "projects/your_project_id/messages/abc123"
}

```

On failure:

```
Failed to send notification: Failed to send notification.
Error details: {
    "error": {
        "code": 400,
        "message": "Invalid value at 'message.data[3].value' (TYPE_STRING), 0"
    }
}

```

Usage
-----

[](#usage)

### Retrieving Data

[](#retrieving-data)

You can retrieve data from your database table using the `getDynamicSearchData` method.

```
use Illuminate\Http\Request;

$searchColumns = [
    // Specify your searchable columns here
];

$helper = new DynamicSearchHelper(
    request: $request,
    searchColumns: $searchColumns,
    withPagination: true,
    queryMode: false,
    isApi: true
);

$result = $helper->getDynamicSearchData();
```

### Search Functionality

[](#search-functionality)

You can enable search functionality by providing columns and relationships to search in.

```
// Define search value, columns, and relationships
$searchColumns = ['column1','relationshipMethod.column2','relationshipMethod1.relationshipMethod2.column3','relationshipMethod3.relationshipMethod4.relationshipMethod5.relationshipMethod6.column8'];
```

### Pagination

[](#pagination)

Pagination is applied automatically based on the request parameters.

Constructor Parameters
----------------------

[](#constructor-parameters)

- `$request` (Illuminate\\Http\\Request)
- `$searchColumns` (array): An array specifying columns to search in
- `$withPagination` (bool): Specifying paginate data or not
- `$queryMode` (bool): Specifying data from the provided Eloquent model
- `$isApi` (bool): Specifying data format

Methods
-------

[](#methods)

`getDynamicSearchData(): Illuminate\Support\Collection`Retrieve dynamic search data from the provided Eloquent model.

### Example

[](#example)

Here's an example of how you can utilize these methods in your controller:

```
use Illuminate\Http\Request;
use ChandraHemant\HtkcUtils\DynamicSearchHelper;

class YourController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();

        $helper = new DynamicSearchHelper(
            request: $request,
            searchColumns: ['unique_id' => $user->unique_id],
            withPagination: true,
            queryMode: false,
            isApi: false,
        );

        // Get the dynamic search data
        $data = $helper->getDynamicSearchData();

        return view('your_view', compact('data'));
    }
}
```

Conclusion
----------

[](#conclusion)

This guide provides a comprehensive overview of how to use the `DynamicSearchHelper` class in your Laravel application. By following these instructions, you can easily implement dynamic search functionality and utilize various helper methods for common tasks.

How to Use
----------

[](#how-to-use)

1. *Installation*: Ensure that the DataTableHelper class is included in your Laravel project.
2. *Initialization*: Create an instance of the DataTableHelper class.
3. *Data Retrieval*: Call the `getDynamicSearchData` method with specified columns, relationship columns, and other parameters to retrieve custom paginated and filtered data.
4. *Customization*: Adjust the class according to your specific use case by modifying the methods or extending its functionality.

#### Note:

[](#note)

Maintaining consistency between the searchColumns array and the actual columns in your model and its relationships is crucial for accurate search results in the DynamicSearchHelper class.

The `searchColumns` array specifies the fields and relationships to be searched within your models. Each element should correspond directly to the columns and relationships defined in your Eloquent models. For instance, if you specify `['orders.product.category.name']` in the `searchColumns`, it assumes that your model has the appropriate relationships `(orders, product, category)` set up correctly and that each relationship has the `name` field available for searching.

To ensure that the dynamic search functionality works seamlessly, double-check that:

- The column names and relationship methods used in `searchColumns` match those defined in your Eloquent models.
- Relationships are correctly defined in your models and are accessible for querying.
- The search functionality aligns with the structure and naming conventions of your database schema.

Inconsistent or incorrect `searchColumns` values may lead to unexpected results or errors, as the helper class will attempt to search across columns and relationships that may not exist or be properly defined.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance40

Moderate activity, may be stable

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~21 days

Recently: every ~1 days

Total

6

Last Release

504d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a1c7527b9e2616683f238599175b442d27c1a35f00638bc9a289ae3d8fe93777?d=identicon)[ChandraHemant](/maintainers/ChandraHemant)

---

Top Contributors

[![ChandraHemant](https://avatars.githubusercontent.com/u/40270385?v=4)](https://github.com/ChandraHemant "ChandraHemant (10 commits)")

---

Tags

phpsearchlaravelmailFCMpush notificationutilsfile-uploaddynamic-searchlaravel-utilsUpload filescustom-searchhtkc-utilsalpha-numeric-generatorcommon-utilscustom-utils

### Embed Badge

![Health badge](/badges/chandra-hemant-htkc-utils/health.svg)

```
[![Health](https://phpackages.com/badges/chandra-hemant-htkc-utils/health.svg)](https://phpackages.com/packages/chandra-hemant-htkc-utils)
```

###  Alternatives

[vemcogroup/laravel-sparkpost-driver

SparkPost driver to use with Laravel 6.x|7.x|8.x|9.x|10.x

421.7M1](/packages/vemcogroup-laravel-sparkpost-driver)[railsware/mailtrap-php

The Mailtrap SDK provides methods for all API functions.

56770.5k](/packages/railsware-mailtrap-php)[bentools/webpush-bundle

Send push notifications through Web Push Protocol to your Symfony users.

71274.3k](/packages/bentools-webpush-bundle)[aksafan/yii2-fcm-both-api

Yii2 Extension for sending push notification with both Firebase Cloud Messaging (FCM) HTTP Server Protocols (APIs).

1552.4k1](/packages/aksafan-yii2-fcm-both-api)[kedniko/firebase-cloud-messaging-http-v1-php

Firebase cloud messaging http v1 php

124.8k](/packages/kedniko-firebase-cloud-messaging-http-v1-php)[juanparati/brevosuite

Complete Brevo integration with Laravel

1010.8k](/packages/juanparati-brevosuite)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
