Build Typescript Interfaces for Laravel Models

Packages

July 27th, 2021

laravel-typescript-featured.png

Laravel Typescript is a package that lets you generate TypeScript interfaces from your Laravel models. The example from the documentation demonstrates how you can take a complex model with database columns and relationships and quickly generate the TypeScript interfaces for them:

1class Product extends Model
2{
3 public function category(): BelongsTo
4 {
5 return $this->belongsTo(Category::class);
6 }
7 
8 public function features(): HasMany
9 {
10 return $this->hasMany(Feature::class);
11 }
12}

The above model will translate into the following interface:

1declare namespace App.Models {
2 export interface Product {
3 id: number;
4 category_id: number;
5 name: string;
6 price: number;
7 created_at: string | null;
8 updated_at: string | null;
9 category?: App.Models.Category | null;
10 features?: Array<App.Models.Feature> | null;
11 }
12 // ...
13}

This package can support database columns, model relationships, model accessors, and planned support for casted attributes.

Finally, here's an example of how you might use this package with a Vue 3 component:

1import { defineComponent, PropType } from "vue";
2 
3export default defineComponent({
4 props: {
5 product: {
6 type: Object as PropType<App.Models.Product>,
7 required: true,
8 },
9 },
10}

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.