laravel-typescript maintained by alexstewartja
Laravel TypeScript
A Laravel package which allows you to quickly generate TypeScript interfaces/definitions for your Eloquent models.
Features
- :white_check_mark: Database columns
- :white_check_mark: Model relations
- :white_check_mark: Model accessors
- :hourglass_flowing_sand: Model casts
- :hourglass_flowing_sand: Inherited relations (Traits/Mixins, etc.)
DBMS Compatibility (Laravel 11+)
- :white_check_mark: pgsql (PostgresSQL)
- :hourglass_flowing_sand: mysql (MySQL)
- :hourglass_flowing_sand: mariadb (MariaDB)
- :hourglass_flowing_sand: sqlsrv (Microsoft SQL Server)
- :hourglass_flowing_sand: 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" :drum:
- All Contributors
License
The MIT License (MIT). Please see License File for more information.