Blog Detail

28

Jul
How to Build Typescript Interfaces for Laravel Models cover image

How to Build Typescript Interfaces for Laravel Models

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.

Published at : 28-07-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

web application development client
web application development client
web application development client
web application development client
web application development client

Launch project