alexstewartja / laravel-typescript
Generate TypeScript interfaces/definitions from Eloquent models
Fund package maintenance!
alexstewartja
Buy Me A Coffee
Requires
- php: ^8.0|^8.1|^8.2|^8.3|^8.4
- doctrine/dbal: ^3.9.4|^4.2.3
- illuminate/contracts: ^8.0|^9.0|^10.0|^11.0|^12.0
- spatie/laravel-package-tools: ^1.92.0
Requires (Dev)
- brianium/paratest: ^6.11.1|^7.4.8
- larastan/larastan: ^1.0.4|^2.0.1|^3.0.0
- nunomaduro/collision: ^5.3|^6.0.0|^7.12.0|^8.7.0
- orchestra/testbench: ^6.15|^7.0.1|^8.0|^9.0|^10.0
- phpunit/phpunit: ^9.3|^10.0|^11.0|^12.0
README
A Laravel package which allows you to quickly generate TypeScript interfaces/definitions for your Eloquent models.
Features
- ✅ Database columns
- ✅ Model relations
- ✅ Model accessors
- ⏳ Model casts
- ⏳ Inherited relations (Traits/Mixins, etc.)
DBMS Compatibility (Laravel 11+)
- ✅ pgsql (PostgresSQL)
- ⏳ mysql (MySQL)
- ⏳ mariadb (MariaDB)
- ⏳ sqlsrv (Microsoft SQL Server)
- ⏳ sqlite (SQLite)
Installation
You can install the package via composer:
composer require alexstewartja/laravel-typescript
Configuration
Publish the config file (config/laravel-typescript.php
) with:
php artisan vendor:publish --provider="AlexStewartJa\TypeScript\TypeScriptServiceProvider" --tag="typescript-config"
Usage
Generate TypeScript interfaces for your Eloquent Models:
php artisan laravel-typescript:generate
Example
Eloquent Model
As an example, the following Product model is defined in an eCommerce app:
class Product extends Model { protected $fillable = [ 'name', 'price', ]; public function category(): BelongsTo { return $this->belongsTo(Category::class); } public function features(): HasMany { return $this->hasMany(Feature::class); } }
TypeScript Interface
Laravel TypeScript will generate the following TypeScript interface:
declare namespace App.Models { export interface Product { id: number; category_id: number; name: string; price: number; created_at: string | null; updated_at: string | null; category?: App.Models.Category | null; features?: Array<App.Models.Feature> | null; } }
TS Interface Usage
This is an example usage with Vue 3:
import { defineComponent, PropType } from "vue"; export default defineComponent({ props: { product: { type: Object as PropType<App.Models.Product>, required: true, }, }, });
And another Vue 3 example for InertiaJS:
interface CartPageProps { products?: Array<App.Models.Product> | null; coupon_code?: string; } defineProps<CartPageProps>();
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
A Lando file is included in the repo to get up and running quickly:
lando start
Please see CONTRIBUTING for more details.
Security
Please see SECURITY for more details.
Credits
- Alex Stewart
- Boris Lepikhin - For developing the foundation on which this package is "based" 🥁
- All Contributors
License
The MIT License (MIT). Please see License File for more information.