PHPackages                             kahil-raghed/laravel-resource-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. kahil-raghed/laravel-resource-helpers

ActiveLibrary[API Development](/categories/api)

kahil-raghed/laravel-resource-helpers
=====================================

Laravel api resource usefull traits

v1.0.0(3mo ago)20MITPHPPHP &gt;=8.0

Since Feb 1Pushed 3mo agoCompare

[ Source](https://github.com/kahil-raghed/laravel-resource-helpers)[ Packagist](https://packagist.org/packages/kahil-raghed/laravel-resource-helpers)[ RSS](/packages/kahil-raghed-laravel-resource-helpers/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (2)Used By (0)

Laravel Resource Helpers
========================

[](#laravel-resource-helpers)

A collection of useful traits for Laravel API Resources that simplify common data transformation tasks.

Overview
--------

[](#overview)

Laravel Resource Helpers is a lightweight package that provides reusable traits for Laravel's API Resources. It helps you handle common scenarios like formatting dates, transforming enums, handling optional fields, and generating asset URLs with minimal boilerplate code.

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

[](#requirements)

- PHP &gt;= 8.0
- Laravel 8.x, 9.x, 10.x, 11.x, 12.x
- Carbon ^2.73

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

[](#installation)

Install the package via Composer:

```
composer require kahil-raghed/laravel-resource-helpers
```

Features
--------

[](#features)

### Available Traits

[](#available-traits)

- **WithResourceHelpers** - Main trait that includes all other traits
- **WithOptional** - Handle optional/conditionally selected fields
- **WithAsset** - Transform storage paths to full asset URLs
- **WithDate** - Format date fields
- **WithDatetime** - Format datetime fields
- **WithTime** - Format time fields
- **WithEnum** - Transform PHP enums to structured arrays

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

[](#configuration)

### Global Configuration

[](#global-configuration)

You can customize default formats globally using the `ResourceHelpers` class:

```
use LaravelResourceHelpers\ResourceHelpers;

// In a service provider's boot method
ResourceHelpers::dateFormat('d/m/Y');
ResourceHelpers::timeFormat('h:i A');
ResourceHelpers::datetimeFormat('d/m/Y h:i A');
```

### Custom Base Model

[](#custom-base-model)

If you're using a custom base model class instead of Eloquent's default:

```
ResourceHelpers::baseModel(YourCustomModel::class);
```

### Custom Enum Resource

[](#custom-enum-resource)

To use a custom enum resource instead of the default:

```
ResourceHelpers::enumResource(YourCustomEnumResource::class);
```

Usage
-----

[](#usage)

### Quick Start

[](#quick-start)

Include the main trait in your API Resource:

```
use Illuminate\Http\Resources\Json\JsonResource;
use LaravelResourceHelpers\Traits\WithResourceHelpers;

class UserResource extends JsonResource
{
    use WithResourceHelpers;

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'created_at' => $this->datetime('created_at'),
            'birth_date' => $this->optionalDate('birth_date'),
            'avatar' => $this->asset('avatar'),
            'status' => $this->enum('status'),
        ];
    }
}
```

### WithOptional

[](#withoptional)

Handle fields that might not be loaded or selected from the database:

```
public function toArray($request)
{
    return [
        'id' => $this->id,
        'email' => $this->optional('email'),
        'phone' => $this->optional('phone', fn($value) => format_phone($value)),
    ];
}
```

**Methods:**

- `optional(string $key, callable|null $transform = null): mixed` - Returns the field value if it exists, or a `MissingValue` if not (which Laravel will exclude from the response)
- If the field exists but has null value it will be returned

### WithAsset

[](#withasset)

Transform storage paths to full asset URLs:

```
public function toArray($request)
{
    return [
        'avatar' => $this->asset('avatar'),
        'cover_image' => $this->optionalAsset('cover_image'),
        'gallery' => $this->assets('gallery'), // For arrays/collections
    ];
}
```

**Methods:**

- `asset(string $key): mixed` - Converts `path/to/file.jpg` to `http://yoursite.com/storage/path/to/file.jpg`
- `assets(string $key): mixed` - Same as `asset()` but for arrays or collections of paths
- `optionalAsset(string $key): mixed` - Optional version that handles missing fields

### WithDate

[](#withdate)

Format date fields with a consistent format:

```
public function toArray($request)
{
    return [
        'birth_date' => $this->date('birth_date'),
        'joined_date' => $this->optionalDate('joined_date'),
    ];
}
```

**Methods:**

- `date(string $key): mixed` - Formats a date using the configured format (default: `Y-m-d`)
- `optionalDate(string $key): mixed` - Optional version that handles missing fields

**Default format:** `Y-m-d` (e.g., `2026-02-01`)

### WithDatetime

[](#withdatetime)

Format datetime fields:

```
public function toArray($request)
{
    return [
        'created_at' => $this->datetime('created_at'),
        'updated_at' => $this->optionalDatetime('updated_at'),
    ];
}
```

**Methods:**

- `datetime(string $key): mixed` - Formats a datetime using the configured format (default: `Y-m-d H:i`)
- `optionalDatetime(string $key): mixed` - Optional version that handles missing fields

**Default format:** `Y-m-d H:i` (e.g., `2026-02-01 14:30`)

### WithTime

[](#withtime)

Format time fields:

```
public function toArray($request)
{
    return [
        'start_time' => $this->time('start_time'),
        'end_time' => $this->optionalTime('end_time'),
    ];
}
```

**Methods:**

- `time(string $key): mixed` - Formats a time using the configured format (default: `H:i`)
- `optionalTime(string $key): mixed` - Optional version that handles missing fields

**Default format:** `H:i` (e.g., `14:30`)

### WithEnum

[](#withenum)

Transform PHP enums to structured arrays:

```
enum UserStatus: string
{
    case Active = 'active';
    case Inactive = 'inactive';
    case Suspended = 'suspended';

    public function label(): string
    {
        return match($this) {
            self::Active => 'Active User',
            self::Inactive => 'Inactive User',
            self::Suspended => 'Suspended User',
        };
    }
}

class UserResource extends JsonResource
{
    use WithResourceHelpers;

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'status' => $this->enum('status'),
            'role' => $this->optionalEnum('role'),
        ];
    }
}
```

**Output:**

```
{
    "id": 1,
    "status": {
        "name": "Active",
        "value": "active",
        "label": "Active User"
    }
}
```

**Methods:**

- `enum(string $key): mixed` - Transforms an enum to a resource
- `optionalEnum(string $key): mixed` - Optional version that handles missing fields

The `EnumResource` includes:

- `name` - The enum case name
- `value` - The backed value (only for `BackedEnum`)
- `label` - Custom label if a `label()` method is defined on the enum

Advanced Examples
-----------------

[](#advanced-examples)

### Combining Multiple Traits

[](#combining-multiple-traits)

You can use individual traits if you don't need all features:

```
use LaravelResourceHelpers\Traits\WithOptional;
use LaravelResourceHelpers\Traits\WithDate;
use LaravelResourceHelpers\Traits\WithAsset;

class ProductResource extends JsonResource
{
    use WithOptional, WithDate, WithAsset;

    public function toArray($request)
    {
        return [
            'name' => $this->name,
            'image' => $this->asset('image'),
            'release_date' => $this->optionalDate('release_date'),
        ];
    }
}
```

### Selective Field Loading

[](#selective-field-loading)

The `optional()` method works great with Laravel's selective column loading:

```
// Controller
public function index()
{
    // Only load specific columns
    $users = User::select(['id', 'name', 'email'])->get();

    return UserResource::collection($users);
}

// Resource
class UserResource extends JsonResource
{
    use WithResourceHelpers;

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->optional('email'),
            'phone' => $this->optional('phone'), // Won't be included since not selected
            'address' => $this->optional('address'), // Won't be included since not selected
        ];
    }
}
```

### Custom Transformations

[](#custom-transformations)

The `optional()` method accepts a transformation callback:

```
public function toArray($request)
{
    return [
        'price' => $this->optional('price', fn($value) => number_format($value, 2)),
        'phone' => $this->optional('phone', fn($value) => preg_replace('/[^0-9]/', '', $value)),
        'tags' => $this->optional('tags', fn($value) => explode(',', $value)),
    ];
}
```

API Reference
-------------

[](#api-reference)

### ResourceHelpers Class

[](#resourcehelpers-class)

Static configuration class for global settings.

#### Methods

[](#methods)

- `baseModel(?string $modelClass = null): string` - Get or set the base model class
- `enumResource(?string $resourceClass = null): string` - Get or set the enum resource class
- `dateFormat(?string $format = null): string` - Get or set the date format
- `timeFormat(?string $format = null): string` - Get or set the time format
- `datetimeFormat(?string $format = null): string` - Get or set the datetime format

### Default Values

[](#default-values)

- **Date Format:** `Y-m-d`
- **Time Format:** `H:i`
- **Datetime Format:** `Y-m-d H:i`
- **Base Model:** `Illuminate\Database\Eloquent\Model`
- **Enum Resource:** `LaravelResourceHelpers\Resources\EnumResource`

How It Works
------------

[](#how-it-works)

### Optional Fields

[](#optional-fields)

The `WithOptional` trait checks if a field exists in the underlying resource:

- For arrays: checks if the key exists
- For Eloquent models: checks if the attribute exists in the original attributes
- For other objects: checks if the property exists

If the field doesn't exist, it returns a `MissingValue` instance which Laravel's JSON resource will automatically exclude from the response.

### Asset URLs

[](#asset-urls)

The `WithAsset` trait prepends `storage/` to the path and uses Laravel's `asset()` helper to generate the full URL. This assumes your files are stored in the public storage directory.

### Date/Time Formatting

[](#datetime-formatting)

Date, time, and datetime traits use Carbon instances and format them according to the configured formats. They handle null values gracefully.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

This package is open-sourced software licensed under the MIT license.

Author
------

[](#author)

**Raghed Kahil**

- Email:

Credits
-------

[](#credits)

Built with ❤️ for the Laravel community.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance81

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 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

Unknown

Total

1

Last Release

101d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/99bd5025e4a50917fa23ab19d1fee23d40a395529897b9ac3c73fbba278c827b?d=identicon)[kahil-raghed](/maintainers/kahil-raghed)

---

Top Contributors

[![kahil-raghed](https://avatars.githubusercontent.com/u/188712413?v=4)](https://github.com/kahil-raghed "kahil-raghed (2 commits)")

### Embed Badge

![Health badge](/badges/kahil-raghed-laravel-resource-helpers/health.svg)

```
[![Health](https://phpackages.com/badges/kahil-raghed-laravel-resource-helpers/health.svg)](https://phpackages.com/packages/kahil-raghed-laravel-resource-helpers)
```

###  Alternatives

[spatie/laravel-query-builder

Easily build Eloquent queries from API requests

4.4k26.9M220](/packages/spatie-laravel-query-builder)[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[esign/laravel-conversions-api

A laravel wrapper package around the Facebook Conversions API

69145.4k](/packages/esign-laravel-conversions-api)[specialtactics/l5-api

Dependencies for the Laravel API Boilerplate package

3672.8k2](/packages/specialtactics-l5-api)[surface/laravel-webfinger

A Laravel package to create an ActivityPub webfinger.

113.8k](/packages/surface-laravel-webfinger)

PHPackages © 2026

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