PHPackages                             hynek/hynek-laravel-to-zod - 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. hynek/hynek-laravel-to-zod

ActiveLibrary

hynek/hynek-laravel-to-zod
==========================

1.0.0(8mo ago)05MITPHPPHP ^8.2

Since Sep 11Pushed 7mo agoCompare

[ Source](https://github.com/hynek-systems/laravel-to-zod)[ Packagist](https://packagist.org/packages/hynek/hynek-laravel-to-zod)[ RSS](/packages/hynek-hynek-laravel-to-zod/feed)WikiDiscussions main Synced 1mo ago

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

Laravel to Zod Converter
========================

[](#laravel-to-zod-converter)

A PHP package that converts Laravel validation rules to [Zod](https://zod.dev/) schema JavaScript code, enabling seamless validation sharing between your Laravel backend and TypeScript/JavaScript frontend.

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

[](#installation)

Install the package via Composer:

```
composer require hynek/laravel-to-zod
```

The package will automatically register its service provider in Laravel 5.5+.

Basic Usage
-----------

[](#basic-usage)

### Converting Validation Rules

[](#converting-validation-rules)

```
use Hynek\LaravelToZod\LaravelToZodConverter;

// Define your Laravel validation rules
$rules = [
    'name' => 'required|string|max:255',
    'email' => 'required|string|email|max:255|unique:users',
    'age' => 'nullable|integer|min:18|max:120',
    'preferences' => 'array',
    'is_admin' => 'boolean',
];

// Convert to Zod schema
$converter = new LaravelToZodConverter($rules);
$zodSchema = $converter->toZodSchema();

echo $zodSchema;
```

**Output:**

```
import { z } from 'zod';

const schema = z.object({
  name: z.string().max(255),
  email: z.string().email().max(255),
  age: z.number().min(18).max(120).nullable(),
  preferences: z.array(),
  is_admin: z.boolean()
});
```

### Working with Form Requests

[](#working-with-form-requests)

```
use App\Http\Requests\UserRegistrationRequest;
use Hynek\LaravelToZod\LaravelToZodConverter;

class UserController extends Controller
{
    public function getValidationSchema()
    {
        $request = new UserRegistrationRequest();
        $converter = new LaravelToZodConverter($request->rules());

        return response()->json([
            'schema' => $converter->toZodSchema()
        ]);
    }
}
```

Supported Laravel Validation Rules
----------------------------------

[](#supported-laravel-validation-rules)

### Basic Types

[](#basic-types)

- `string` → `z.string()`
- `integer`, `numeric` → `z.number()`
- `boolean` → `z.boolean()`
- `array` → `z.array()`
- `date` → `z.date()`

### String Validations

[](#string-validations)

- `email` → `z.string().email()`
- `url` → `z.string().url()`
- `uuid` → `z.string().uuid()`
- `min:n` → `z.string().min(n)`
- `max:n` → `z.string().max(n)`
- `size:n` → `z.string().length(n)`
- `between:min,max` → `z.string().min(min).max(max)`
- `regex:pattern` → `z.string().regex(/pattern/)`

### Number Validations

[](#number-validations)

- `min:n` → `z.number().min(n)`
- `max:n` → `z.number().max(n)`
- `gt:n` → `z.number().gt(n)`
- `gte:n` → `z.number().gte(n)`
- `lt:n` → `z.number().lt(n)`
- `lte:n` → `z.number().lte(n)`

### Array Validations

[](#array-validations)

- `array` → `z.array()`
- `min:n` → `z.array().min(n)`
- `max:n` → `z.array().max(n)`
- `size:n` → `z.array().length(n)`

### Enum Validations

[](#enum-validations)

- `in:value1,value2,value3` → `z.enum(['value1', 'value2', 'value3'])`

### Modifiers

[](#modifiers)

- `required` → Field is required (default behavior)
- `nullable` → `.nullable()`
- `optional`, `sometimes` → `.optional()`

Advanced Usage
--------------

[](#advanced-usage)

### Nested Field Names

[](#nested-field-names)

The package properly handles nested validation rules with dot notation:

```
$rules = [
    'user.name' => 'required|string|max:50',
    'user.email' => 'required|email',
    'data.preferences' => 'array',
];

$converter = new LaravelToZodConverter($rules);
echo $converter->toZodSchema();
```

**Output:**

```
import { z } from 'zod';

const schema = z.object({
  'user.name': z.string().max(50),
  'user.email': z.string().email(),
  'data.preferences': z.array()
});
```

### Complex Validation Scenarios

[](#complex-validation-scenarios)

```
$rules = [
    'username' => 'required|string|min:3|max:20|regex:/^[a-zA-Z0-9_]+$/',
    'password' => 'required|string|min:8|max:255',
    'confirm_password' => 'required|string|same:password',
    'role' => 'required|in:admin,user,moderator',
    'metadata' => 'sometimes|array',
    'profile.bio' => 'nullable|string|max:1000',
];
```

### API Integration

[](#api-integration)

You can easily expose Zod schemas via API endpoints for frontend consumption:

```
Route::get('/validation-schemas/{form}', function ($form) {
    $rules = match($form) {
        'user-registration' => [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|string|min:8',
        ],
        'product-creation' => [
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
            'category_id' => 'required|integer|exists:categories,id',
        ],
        default => []
    };

    if (empty($rules)) {
        abort(404);
    }

    $converter = new LaravelToZodConverter($rules);

    return response($converter->toZodSchema())
        ->header('Content-Type', 'application/javascript');
});
```

### Frontend Usage

[](#frontend-usage)

Once you have the Zod schema, you can use it in your TypeScript/JavaScript frontend:

```
// Fetch the schema from your Laravel API
const response = await fetch('/validation-schemas/user-registration');
const schemaCode = await response.text();

// The schema code can be evaluated or saved to a file
// For example, save it as userRegistrationSchema.js and import it:

import { schema } from './userRegistrationSchema.js';

// Use the schema for validation
const result = schema.safeParse(formData);

if (!result.success) {
    console.log('Validation errors:', result.error.issues);
} else {
    console.log('Valid data:', result.data);
}
```

Output Formats
--------------

[](#output-formats)

The package provides two output formats:

### 1. Zod Schema JavaScript (default)

[](#1-zod-schema-javascript-default)

```
$converter->toZodSchema(); // Returns complete JavaScript code
```

### 2. JSON Structure

[](#2-json-structure)

```
$converter->toJSON(); // Returns JSON representation of the schema structure
```

Testing
-------

[](#testing)

The package includes comprehensive tests using Pest PHP:

```
# Run all tests
./vendor/bin/pest

# Run specific test suites
./vendor/bin/pest tests/Unit
./vendor/bin/pest tests/Feature

# Run with coverage
./vendor/bin/pest --coverage
```

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

[](#requirements)

- PHP 8.1+
- Laravel 9.0+

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](LICENSE).

Changelog
---------

[](#changelog)

### 1.0.0

[](#100)

- Initial release
- Support for basic Laravel validation rules
- Zod schema generation
- Comprehensive test suite

---

For more information about Zod, visit the [official Zod documentation](https://zod.dev/).

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance62

Regular maintenance activity

Popularity4

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

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

243d ago

### Community

Maintainers

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

---

Tags

laravelmodulehynek

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/hynek-hynek-laravel-to-zod/health.svg)

```
[![Health](https://phpackages.com/badges/hynek-hynek-laravel-to-zod/health.svg)](https://phpackages.com/packages/hynek-hynek-laravel-to-zod)
```

###  Alternatives

[internachi/modular

Modularize your Laravel apps

1.1k662.4k8](/packages/internachi-modular)[pingpong/modules

Laravel Modules

592188.7k13](/packages/pingpong-modules)[yajra/cms-core

Core module of YajraCMS.

201.8k1](/packages/yajra-cms-core)

PHPackages © 2026

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