PHPackages                             labelgrup/laravel-utilities - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. labelgrup/laravel-utilities

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

labelgrup/laravel-utilities
===========================

Utilities to Laravel projects

39.5k↓26.9%1PHP

Since Feb 25Pushed 2mo ago2 watchersCompare

[ Source](https://github.com/labelgrupnetworks/laravel-utilities)[ Packagist](https://packagist.org/packages/labelgrup/laravel-utilities)[ RSS](/packages/labelgrup-laravel-utilities/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)DependenciesVersions (2)Used By (0)

Laravel Utilities 🛠️ [![Public Repository Badge](https://camo.githubusercontent.com/9e8d5c63a32c3052b5576c5d0ceb9f7084da1819634e6ba7f956b47c359ba61d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7265706f7369746f72792d7075626c69632d677265656e2e7376673f6c6f676f3d6c61726176656c)](https://camo.githubusercontent.com/9e8d5c63a32c3052b5576c5d0ceb9f7084da1819634e6ba7f956b47c359ba61d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7265706f7369746f72792d7075626c69632d677265656e2e7376673f6c6f676f3d6c61726176656c)
=================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#laravel-utilities-️-)

A comprehensive collection of utilities to improve and streamline Laravel applications. This package provides Artisan commands for scaffolding API-ready components, reusable helper classes, custom exception handling, validation rules, and support for modern API development patterns.

✅ Requirements
--------------

[](#-requirements)

- PHP `^8.0`
- Laravel `^9.2|^10.0|^11.0|^12.0|^13.0`
- PHP Extensions: `zip`, `curl`

📦 Installation
--------------

[](#-installation)

```
composer require labelgrup/laravel-utilities
```

The package is automatically registered through Laravel's package discovery.

📚 Table of Contents
-------------------

[](#-table-of-contents)

- [Commands](#-commands)
    - [MakeApiRequest](#-makeapirequest)
    - [MakeUseCase](#-makeusecase)
- [Core Classes](#-core-classes)
    - [ApiRequest](#apirequest)
    - [UseCase &amp; UseCaseInterface](#usecase--usecaseinterface)
    - [UseCaseResponse](#usecaseresponse)
- [CustomException](#-customexception)
- [Helpers](#-helpers)
    - [ApiResponse](#apiresponse)
    - [ExceptionHandler](#exceptionhandler)
    - [Image](#image)
    - [Password](#password)
    - [Text](#text)
    - [Time](#time)
    - [Zip](#zip)
- [Validation Rules](#-validation-rules)
    - [SlugRule](#slugrule)

---

⚙️ Commands
-----------

[](#️-commands)

### 📝 MakeApiRequest

[](#-makeapirequest)

Generates an API request class in **`app/Http/Requests/Api/`** with built-in JSON validation error handling.

```
php artisan make:api-request {ApiRequestName}
```

The generated class extends `ApiRequest` and provides automatic JSON response formatting for validation failures. It's designed to work seamlessly with API endpoints.

**Example Usage:**

```
namespace App\Http\Requests\Api;

use Labelgrup\LaravelUtilities\Core\Requests\ApiRequest;

class CreateUserRequest extends ApiRequest
{
    public function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8'
        ];
    }
}
```

### 🧠 MakeUseCase

[](#-makeusecase)

Generates a **Use Case** class in **`app/UseCases/`** to encapsulate and organize business logic into reusable, testable actions.

```
php artisan make:use-case {UseCaseName} {--without-validation}
```

The generated class extends `UseCase`, implements `UseCaseInterface`, and includes built-in exception handling and response management.

**Example with Validation:**

```
namespace App\UseCases;

use Labelgrup\LaravelUtilities\Core\UseCases\UseCase;
use Labelgrup\LaravelUtilities\Core\UseCases\WithValidateInterface;

class CreateUserUseCase extends UseCase implements WithValidateInterface
{
    public function __construct(
        private UserRepository $userRepository
    ) {}

    public function action()
    {
        // Your business logic here
        return $this->userRepository->create($this->getData());
    }

    public function validate(): void
    {
        $validator = validator($this->getData(), [
            'name' => 'required|string',
            'email' => 'required|email|unique:users'
        ]);

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }
    }
}
```

**Customizing Response:**

```
public string $response_message = 'User created successfully';
public int $success_status_code = 201; // HTTP_CREATED

// Or override the handle() method for complete control
public function handle(): UseCaseResponse
{
    // Custom logic here
    return parent::handle();
}
```

---

🏗️ Core Classes
---------------

[](#️-core-classes)

### ApiRequest

[](#apirequest)

Located in `src/Core/Requests/ApiRequest.php`, this abstract class extends Laravel's `FormRequest` and automatically formats validation errors as JSON responses, making it ideal for API controllers.

**Features:**

- Automatic JSON error responses for validation failures
- Uses `ApiResponse::fail()` for consistent error formatting
- Returns HTTP 422 (Unprocessable Entity) on validation error

### UseCase &amp; UseCaseInterface

[](#usecase--usecaseinterface)

Located in `src/Core/UseCases/`, these classes provide a pattern for organizing business logic.

**UseCase Class:**

- Abstract base class with built-in exception handling
- Calls `validate()` automatically if the `WithValidateInterface` is implemented
- Wraps errors in `UseCaseResponse` with proper HTTP status codes
- Configurable `success_status_code` and `response_message`

**UseCaseInterface:**Requires implementation of the `action()` method, which contains your business logic.

### UseCaseResponse

[](#usecaseresponse)

A standardized response object returned by all Use Cases containing:

- `success` (bool) - Whether the operation succeeded
- `message` (string) - Response message
- `http_code` (int) - HTTP status code
- `data` (mixed) - Response payload
- `error_code` (string|null) - Custom error code for logging/debugging
- `trace` (array) - Exception trace (only on failures)

---

❗ CustomException
-----------------

[](#-customexception)

Provides a custom exception class that extends `Exception` and implements Laravel's `Renderable` interface for fine-grained control over API error responses.

```
public function __construct(
    public string $error_code,
    public string $error_message,
    public int $http_code = Response::HTTP_INTERNAL_SERVER_ERROR,
    public ?array $report_data = ['logs' => []],
    public ?array $response = [],
    public bool $should_render = true
)
```

**Parameters:**

- `error_code`: Unique identifier for the exception (e.g., `'USER_NOT_FOUND'`)
- `error_message`: Human-readable error message
- `http_code`: HTTP status code (defaults to 500)
- `report_data`: Additional context for logging
- `response`: Custom response data
- `should_render`: Whether to render the exception

**Example Usage:**

```
throw new CustomException(
    error_code: 'USER_NOT_FOUND',
    error_message: 'The requested user does not exist',
    http_code: Response::HTTP_NOT_FOUND
);
```

**Automatic Logging:**The exception automatically logs request information including method, parameters, and user context when reported.

---

🔧 Helpers
---------

[](#-helpers)

### ApiResponse

[](#apiresponse)

Provides fluent methods for consistent API response formatting.

**Available Methods:**

**`ok(data, code = 200, streamJson = false): JsonResponse|StreamedJsonResponse`**Returns a success response with data only.

```
return ApiResponse::ok(['users' => $users]);
```

**`done(message, data = [], code = 200, streamJson = false): JsonResponse|StreamedJsonResponse`**Returns a success response with message and optional data.

```
return ApiResponse::done('Users retrieved successfully', ['users' => $users]);
```

**`fail(message, data = [], code = 400, error_code = null, trace = []): JsonResponse|StreamedJsonResponse`**Returns a failure response with error information.

```
return ApiResponse::fail('Validation failed', $errors, Response::HTTP_UNPROCESSABLE_ENTITY);
```

**`stream(data): StreamedJsonResponse`**Returns a streamed JSON response for large datasets.

```
return ApiResponse::stream($largeDataset);
```

### ExceptionHandler

[](#exceptionhandler)

Provides a centralized exception rendering system for both legacy (Laravel &lt;11) and current Laravel versions.

**Static `render()` Method:**Handles rendering of various exception types including:

- `CustomException` - Custom error responses
- `ValidationException` - Validation error responses
- `AuthenticationException` - Authentication failures (401)
- `UnauthorizedException` - Authorization failures (401)
- `NotFoundHttpException` - Resource not found (404)
- `HttpException` - Generic HTTP exceptions

**Usage in Exception Handler:**

```
public function render($request, Throwable $exception)
{
    return ExceptionHandler::render($exception, $request);
}
```

### Image

[](#image)

Provides image manipulation utilities.

**`getExtensionImageFromUrl(url): ?string`**Extracts the file extension from an image URL.

```
$ext = Image::getExtensionImageFromUrl('https://example.com/image.jpg'); // 'jpg'
```

**`destroy(src): bool`**Deletes an image from storage.

```
Image::destroy('uploads/profile.jpg'); // true/false
```

**`downloadFromUrl(url, fileName): void`**Downloads an image from a URL and saves it locally. Uses cURL with proper headers and timeouts.

```
Image::downloadFromUrl('https://example.com/avatar.png', 'local_avatar.png');
```

### Password

[](#password)

Provides password generation and validation with security checks.

**`rule(min_size = 12): PasswordRule`**Returns a validated password rule with requirements:

- Minimum length (default 12 characters)
- Mixed case letters
- Numbers
- Symbols
- Must not be in known leaked password databases

```
'password' => [
    'required',
    'confirmed',
    Password::rule(16) // Minimum 16 characters
]
```

**`generateSecurePassword(length = 12, max_retries = 5): string`**Generates a cryptographically secure random password that is not in breach databases.

Attempts up to `max_retries` times to generate a password not found in leaked password databases.

```
$password = Password::generateSecurePassword(16); // length: 16
```

### Text

[](#text)

String manipulation utilities with UTF-8 support.

**`sanitize(text, divider = '-'): string`**Sanitizes text for URL-safe slugs:

- Removes non-alphanumeric characters
- Converts to ASCII transliteration
- Lowercases the result
- Removes duplicate separators
- Returns 'n-a' for empty results

```
Text::sanitize('Héllo Wørld!'); // 'hello-world'
Text::sanitize('User Profile', '_'); // 'user_profile'
```

### Time

[](#time)

Converts seconds to human-readable time format.

**`parseTimeForHumans(seconds, unitMin = 's'): string`**Breaks down seconds into readable time units (weeks, days, hours, minutes, seconds).

- `unitMin` parameter controls the minimum unit to display:
    - `'s'` - seconds (default)
    - `'i'` - minutes
    - `'h'` - hours
    - `'d'` - days
    - `'w'` - weeks

```
Time::parseTimeForHumans(3661); // '1 hour 1 minute 1 second'
Time::parseTimeForHumans(86400, 'h'); // '1 day'
Time::parseTimeForHumans(604800, 'd'); // '1 week'
```

### Zip

[](#zip)

File compression utilities.

**`create(zipFile, sourcePath): ?string`**Creates a ZIP archive from a directory recursively.

Returns the path to the created ZIP file or null on failure.

```
Zip::create(
    storage_path('exports/archive.zip'),
    storage_path('files')
);
```

The method:

- Preserves directory structure
- Includes all files recursively
- Returns the file path on success

---

🎯 Validation Rules
------------------

[](#-validation-rules)

### SlugRule

[](#slugrule)

Validates that a string conforms to valid slug format (`[a-z0-9]+(?:-[a-z0-9]+)*`).

A slug must:

- Contain only lowercase letters and numbers
- Allow hyphens as separators
- Start and end with alphanumeric characters

**Usage:**

```
use Labelgrup\LaravelUtilities\Rules\SlugRule;

'slug' => ['required', 'string', new SlugRule()]

// Valid: product-name, user-profile-123
// Invalid: Product-Name, user_profile, -invalid-
```

---

📄 License
---------

[](#-license)

MIT License. See the LICENSE file for details.

👥 Authors
---------

[](#-authors)

- **Eric RF** -
- **Manel Alonso** -

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance58

Moderate activity, may be stable

Popularity29

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity17

Early-stage or recently created project

 Bus Factor1

Top contributor holds 71.8% 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.

### Community

Maintainers

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

---

Top Contributors

[![erojaslabelgrup](https://avatars.githubusercontent.com/u/65939992?v=4)](https://github.com/erojaslabelgrup "erojaslabelgrup (51 commits)")[![drkbcn](https://avatars.githubusercontent.com/u/2090227?v=4)](https://github.com/drkbcn "drkbcn (11 commits)")[![labelgrupnetworks](https://avatars.githubusercontent.com/u/64518853?v=4)](https://github.com/labelgrupnetworks "labelgrupnetworks (4 commits)")[![rferic](https://avatars.githubusercontent.com/u/14909500?v=4)](https://github.com/rferic "rferic (4 commits)")[![malonsolabelgrup](https://avatars.githubusercontent.com/u/64540623?v=4)](https://github.com/malonsolabelgrup "malonsolabelgrup (1 commits)")

### Embed Badge

![Health badge](/badges/labelgrup-laravel-utilities/health.svg)

```
[![Health](https://phpackages.com/badges/labelgrup-laravel-utilities/health.svg)](https://phpackages.com/packages/labelgrup-laravel-utilities)
```

###  Alternatives

[ournameismud/fractal

Custom Fractal plugin

148.7k1](/packages/ournameismud-fractal)

PHPackages © 2026

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