PHPackages                             mainul/custom-helpers - 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. [API Development](/categories/api)
4. /
5. mainul/custom-helpers

ActiveLibrary[API Development](/categories/api)

mainul/custom-helpers
=====================

A Laravel package providing helper functions for API and web responses

v1.1.9(3mo ago)035MITPHPPHP ^8.2

Since Dec 22Pushed 3mo agoCompare

[ Source](https://github.com/Mainul12501/custom-helpers)[ Packagist](https://packagist.org/packages/mainul/custom-helpers)[ RSS](/packages/mainul-custom-helpers/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (5)Versions (12)Used By (0)

Helper Functions Package for Laravel
====================================

[](#helper-functions-package-for-laravel)

A Laravel package providing comprehensive helper functions for handling API and web responses, authentication, code generation, date formatting, file uploads, and more.

Requirements
------------

[](#requirements)

- PHP &gt;= 8.2
- Laravel 11.x or 12.x

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

[](#installation)

### Step 1: Install via Composer

[](#step-1-install-via-composer)

```
composer require mainul/custom-helpers
```

### Step 2: Publish Configuration (Optional)

[](#step-2-publish-configuration-optional)

Publish the configuration file to customize package settings:

```
php artisan vendor:publish --tag=helper-functions-config
```

This will create a `config/helper-functions.php` file where you can customize:

- Route settings (prefix, middleware)
- Default error messages
- API detection patterns
- And more

### Step 3: Publish Routes (Optional)

[](#step-3-publish-routes-optional)

If you want to customize the routes, publish the route files:

```
php artisan vendor:publish --tag=helper-functions-routes
```

This will create:

- `routes/helper-functions-web.php`
- `routes/helper-functions-api.php`

You can then update the routes in these files and disable the package routes in `config/helper-functions.php`:

```
'routes' => [
    'web' => [
        'enabled' => false, // Disable package web routes
    ],
    'api' => [
        'enabled' => false, // Disable package API routes
    ],
],
```

Configuration
-------------

[](#configuration)

After publishing the config file, you can customize the package in `config/helper-functions.php`:

### Routes Configuration

[](#routes-configuration)

```
'routes' => [
    'web' => [
        'enabled' => true,              // Enable/disable web routes
        'prefix' => null,               // Route prefix
        'middleware' => ['web'],        // Middleware groups
    ],
    'api' => [
        'enabled' => true,              // Enable/disable API routes
        'prefix' => 'api',              // Route prefix
        'middleware' => ['api'],        // Middleware groups
    ],
],
```

### CustomHelper Configuration

[](#customhelper-configuration)

```
'custom_helper' => [
    'default_error_message' => 'Something went wrong. Please try again.',
    'no_data_message' => 'No Data found.',
    'default_success_message' => 'Operation completed successfully.',
    'api_guard' => 'sanctum',           // Auth guard for API
    'default_guard' => null,            // Default auth guard
],
```

Usage
-----

[](#usage)

### Using the CustomHelper Class

[](#using-the-customhelper-class)

```
use Mainul\CustomHelperFunctions\Helpers\CustomHelper;

// Return data for web or API
return CustomHelper::returnDataForWebOrApi($data, 'users.index', $errorMessage);

// Return success message
return CustomHelper::returnSuccessMessage('User created successfully');

// Check authentication
if (CustomHelper::authCheck()) {
    $user = CustomHelper::loggedUser();
}

// Generate code (OTP)
$otp = CustomHelper::generateCode(6, 'number');

// Get session code
$sessionCode = CustomHelper::getSessionCode('mobile_123');
```

Available Methods
-----------------

[](#available-methods)

### Response Methods

[](#response-methods)

MethodDescription`returnDataForWebOrApi($data, $viewPath, $jsonErrorMessage, $isForRender, $isReturnBack, $successMsg)`Return JSON for API/AJAX or view for web requests`returErrorMessage($message, $customMsg)`Return error response for API or redirect back with error for web`returnSuccessMessage($message)`Return success response for API or redirect back with success for web`returnRedirectWithMessage($route, $messageType, $message)`Redirect to route with message (handles API/AJAX/web)### Request Detection Methods

[](#request-detection-methods)

MethodDescription`isApiRequest()`Check if current request is an API request`isAjax()`Check if current request is an AJAX request`wantsJsonResponse()`Check if request wants JSON response (API or AJAX)### Authentication Methods

[](#authentication-methods)

MethodDescription`authCheck()`Check if user is authenticated (uses sanctum for API, default guard for web)`loggedUser()`Get the currently logged-in user### Code Generation Methods

[](#code-generation-methods)

MethodDescription`generateCode($length, $type)`Generate code - supports `number`, `alpha`, or `random` (alphanumeric)`generateSessionCode($length, $type, $sessionKey)`Generate and store code in session/cache`getSessionCode($sessionKey)`Retrieve generated code from session/cache### Date &amp; Time Methods

[](#date--time-methods)

MethodDescription`showDate($date)`Format date as `d-m-Y` (e.g., 25-12-2024)`showTime($date)`Format time as `g:i A` (e.g., 3:30 PM)`showDateTime($date)`Format as `d-m-Y g:i A` (e.g., 25-12-2024 3:30 PM)`showDateTime24Hours($date)`Format as `d-m-Y H:i` (e.g., 25-12-2024 15:30)`showDateForBlogType($date)`Format as `F d, Y` (e.g., December 25, 2024)`dateWithTime($date)`Format as `Y-m-d H:i``currentDateWithTime()`Get current date and time as `Y-m-d H:i``getDurationAmongTwoDates($startDate, $endDate, $durationUnit, $isEndDateIsCurrentDate)`Calculate duration between dates (years/months/days)`differTime($start, $end, $info)`Get human-readable time difference### File Methods

[](#file-methods)

MethodDescription`getFileExtension($file)`Get file extension`getFileType($file)`Get file MIME type`fileUpload($fileObject, $directory, $nameString, $modelFileUrl)`Upload file to specified directory`fileUploadByBase64($base64String, $imageDirectory, $imageNameString, $modelFileUrl)`Upload file from base64 string### Artisan Command Methods

[](#artisan-command-methods)

MethodDescription`startQueueWorkManuallyByArtisanCommand()`Manually process the queue`clearRouteCache()`Clear route cache`CacheRoute()`Cache routes`optimizeClear()`Clear all optimizations`clearCache()`Clear application cache### Controller Methods (CustomHelperController)

[](#controller-methods-customhelpercontroller)

Route MethodDescription`symlink()`Create storage symbolic link`optimizeReset()`Clear all optimizations and return output`phpinfo()`Display PHP informationAdding Custom Routes
--------------------

[](#adding-custom-routes)

### Option 1: Edit Package Routes Directly (Not Recommended)

[](#option-1-edit-package-routes-directly-not-recommended)

Edit `src/routes/web.php` or `src/routes/api.php`:

```
use Illuminate\Support\Facades\Route;
use Mainul\CustomHelperFunctions\Helpers\CustomHelper;

Route::get('/your-route', function () {
    // Your logic here
});
```

### Option 2: Publish and Customize Routes (Recommended)

[](#option-2-publish-and-customize-routes-recommended)

1. Publish routes:

```
php artisan vendor:publish --tag=helper-functions-routes
```

2. Edit published routes in `routes/helper-functions-web.php` or `routes/helper-functions-api.php`
3. Disable package routes in `config/helper-functions.php`:

```
'routes' => [
    'web' => ['enabled' => false],
    'api' => ['enabled' => false],
],
```

4. Load your custom routes in `app/Providers/AppServiceProvider.php`:

```
public function boot()
{
    $this->loadRoutesFrom(base_path('routes/helper-functions-web.php'));
    $this->loadRoutesFrom(base_path('routes/helper-functions-api.php'));
}
```

Optional Dependencies
---------------------

[](#optional-dependencies)

The package works with these optional packages:

- `brian2694/laravel-toastr` - For flash messages (optional)

If this package is not installed, the package will skip the related functionality.

License
-------

[](#license)

MIT

Support
-------

[](#support)

For issues and feature requests, please use the GitHub issue tracker.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance80

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity54

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 ~4 days

Total

11

Last Release

106d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5ff09c9d3ceaf957dae0f365749477680c0eb6d8d7ada9bcc266e3d4b53552a0?d=identicon)[Mainul12501](/maintainers/Mainul12501)

---

Top Contributors

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

---

Tags

responseapilaravelhelper

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mainul-custom-helpers/health.svg)

```
[![Health](https://phpackages.com/badges/mainul-custom-helpers/health.svg)](https://phpackages.com/packages/mainul-custom-helpers)
```

###  Alternatives

[andreaselia/laravel-api-to-postman

Generate a Postman collection automatically from your Laravel API

1.0k586.2k3](/packages/andreaselia-laravel-api-to-postman)[api-ecosystem-for-laravel/dingo-api

A RESTful API package for the Laravel and Lumen frameworks.

3121.5M10](/packages/api-ecosystem-for-laravel-dingo-api)[mtownsend/response-xml

The missing XML support for Laravel's Response class.

1041.2M3](/packages/mtownsend-response-xml)[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)[vinelab/api-manager

Laravel API Manager Package - beatify and unify your responses with the least effort possible.

392.1k](/packages/vinelab-api-manager)

PHPackages © 2026

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