How to Build Typescript Interfaces for Laravel Models

How to Build Typescript Interfaces for Laravel Models cover image

Boris Lepikhin introduced a package known as Laravel Typescript, Which allows you to create TypeScript interfaces from your Laravel models. The example from the documentation shows how you can take a complicated model with database columns and relationships and instantly generate the TypeScript interfaces for them.

Introduction

Suppose you have a model which has various properties (database columns) and multiple relations.

class Product extends Model
{
    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    public function features(): HasMany
    {
        return $this->hasMany(Feature::class);
    }
}

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;
    }
    ...
}

Requirements

  • Laravel 8
  • Php 8

Installation

You’ve to run this command to install the package via composer:

composer require based/laravel-typescript

Next, You’ve to publish the config file with:

php artisan vendor:publish --provider="Based\TypeScript\TypeScriptServiceProvider" --tag="typescript-config"

Usage

Generate TypeScript interfaces.

php artisan typescript:generate

You can utlized it with Vue 3:

import { defineComponent, PropType } from "vue";
export default defineComponent({
    props: {
        product: {
            type: Object as PropType<App.Models.Product>,
            required: true,
        },
    },
}

Laravel TypeScript supports database columns, model relations, and model accessors.

If you want to study more about this package, you can view its full installation instructions and the source code on GitHub.

Written by

Rizwan Aslam

Founder and CEO of CodeBrisk, with years of experience building web applications with Laravel and leading a team of expert developers.

More about Rizwan
Book a free call
Book a call with CodeBrisk