The package lets you generate TypeScript interfaces from your Laravel models.

Overview

Laravel TypeScript

Latest Version on Packagist GitHub Tests Action Status Total Downloads

The package lets you generate TypeScript interfaces from your Laravel models.

Introduction

Say you have a model which has several 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;
    }
    ...
}

Laravel TypeScript supports:

  • Database columns
  • Model relations
  • Model accessors
  • Casted attributes

Installation

Laravel 8 and PHP 8 are required. You can install the package via composer:

composer require based/laravel-typescript

You can publish the config file with:

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

This is the contents of the published config file:

return [
    'generators' => [
        Model::class => ModelGenerator::class,
    ],

    'output' => resource_path('js/models.d.ts'),

    // load namespaces from composer's `dev-autoload`
    'autoloadDev' => false,
];

Usage

Generate TypeScript interfaces.

php artisan typescript:generate

Example usage with Vue 3:

, required: true, }, }, } ">
import { defineComponent, PropType } from "vue";

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

Testing

composer test

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Cannot redeclare helpers when running php artisan typescript:generate

    Cannot redeclare helpers when running php artisan typescript:generate

    Getting strange behaviour when running php artisan typescript:generate it appears it's trying to redeclare all the helpers which are auto loaded via composer.json's "autoload" { "files" : [ "app/helpers.php"] }

    $ php artisan typescript:generate
    PHP Fatal error:  Cannot redeclare selectedVesselId() (previously declared in C:\www\workrest\app\helpers.php:25) in C:\www\workrest\app\Core\helpers.php on line 23
    
       Symfony\Component\ErrorHandler\Error\FatalError 
    
      Cannot redeclare selectedVesselId() (previously declared in C:\www\workrest\app\Core\helpers.php:25)
    

    This is only occurring when running typescript:generate, other CLI commands for artisan are working fine e.g.:

    $ php artisan cache:clear
    Application cache cleared!
    
    opened by SlyDave 10
  • feat: generate interfaces from resources

    feat: generate interfaces from resources

    Hi! What do you think about generation from Resources? e.g:

    /**
     * @mixin \App\Models\Ticket
     */
    class SupportResource extends JsonResource
    {
        /**
         * Transform the resource into an array.
         *
         * @param \Illuminate\Http\Request $request
         * @return array
         */
        public function toArray($request): array
        {
            return [
                'id'         => $this->id,
                'title'      => $this->title,
                'message'    => $this->message,
                'created_at' => $this->created_at->diffForHumans(),
                'category'   => [
                    'title' => $this->category->short_title,
                    'hex_color'   => $this->category->hex_color,
                ],
                'status'     => [
                    'title'     => $this->status->title,
                    'hex_color' => $this->status->hex_color,
                ],
            ];
        }
    }
    

    It's possible? If it is, it will be a consistent interface in the backend and frontend.

    opened by ibrunotome 4
  • Various improvements

    Various improvements

    • Add support for custom paths (to load relevant items from 'vendor' folder)
    • Use explicit config values (with fallback) instead of spread operator in command
    • Add the "generate" command to Generator Contract (since this is what's actually called from the TypeScriptGenerator class)
    • Cleanup of generated code (additional white space, information message, etc)
    • A generator for FormRequest classes
    • TODO: Tests for request generator
    opened by chancezeus 3
  • Workaround for lack of enum support by DBAL

    Workaround for lack of enum support by DBAL

    Unfortunately this package does not work if the database has enum columns. DBAL does not support enum column types. In this PR the enum columns are mapped to strings, so we can still use the package when we have enum columns in our database. The TypeScript models will have a string type instead of an enum. Maybe not the best solution to this problem, but maybe it helps others for the time being.

    opened by robmeijerink 1
  • fix: Generate relation names in snake_case

    fix: Generate relation names in snake_case

    By default, Laravel uses snake_case names for multi-word relations. The PR fixes that and adds an assertion. It also fixes composer.json loading that also works in a debugger environment or when tests is run not from project root (for example running using IDE)

    opened by ekvedaras 1
  • Laravel 9 support

    Laravel 9 support

    Got the error during composer installation:

    - Root composer.json requires based/laravel-typescript ^0.0.2 -> satisfiable by based/laravel-typescript[v0.0.2].
    - based/laravel-typescript v0.0.2 requires illuminate/contracts ^8.37 -> found illuminate/contracts[v8.37.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another requ
    ire.
    

    Need support for illuminate/contracts v9

    opened by tekord 0
  • Sort the generated classes by name

    Sort the generated classes by name

    The classes that are generated are done using symfony's finder class, which can return files in any order returned by the filesystem.

    This means that running the typescript:generate command can generate incredibly noisy diffs - whereas at least if it's sorted then the diffs should be slightly more sensible.

    opened by PatrickRose 0
  • Issue when try to generate typescript files

    Issue when try to generate typescript files

    Hello seems awesome this package, I'm trying to use but i have this error:

    image

    If i remove the ripcord package still have differentes class with "Cannot declare class XXX, because the name is already in use

    opened by sefirosweb 0
  • Is this project abandoned?

    Is this project abandoned?

    This project is great but there's a few lingering issues and it doesn't seem like there's any activity?

    I see there's been some small commits like https://github.com/lepikhinb/laravel-typescript/commit/0ccde3251fdf09b0fb69055569a2fadc4230e052 but no commenting on issues/prs?

    opened by n1c 0
  • Make ModelGenerator account for hidden fields

    Make ModelGenerator account for hidden fields

    Make ModelGenerator filter out columns that have been hidden from the serialized representation of the Model (see: https://laravel.com/docs/9.x/eloquent-serialization#hiding-attributes-from-json).

    The hidden attribute is commonly used with fields like password or remember_token.

    Without filtering the types generated for a model misrepresent what is commonly sent by a server for this model:

    {
      "id": 1,
      "name": "Test User",
      "email": "[email protected]",
      "email_verified_at": "2022-06-29T14:51:15.000000Z",
      "created_at": "2022-06-29T09:18:09.000000Z",
      "updated_at": "2022-06-29T09:18:09.000000Z"
    }
    

    for a generated type

    export interface User {
        id: number;
        name: string;
        email: string;
        email_verified_at: string | null;
        created_at: string | null;
        updated_at: string | null;
    }
    

    instead of (without filtering hidden fields)

    export interface User {
        id: number;
        name: string;
        email: string;
        password: string ;
        remember_token: string ;
        email_verified_at: string | null;
        created_at: string | null;
        updated_at: string | null;
    }
    
    opened by dsalex1 0
  • Typo in function name isOneRelattion

    Typo in function name isOneRelattion

    https://github.com/lepikhinb/laravel-typescript/blob/5f2b2958d63c6b36bcd4e3ba44d711da7f49fcca/src/Generators/ModelGenerator.php#L225

    Function isOneRelattion should be renamed to isOneRelation

    opened by royteusink 1
Releases(v0.0.1)
Owner
Boris Lepikhin
Making some tricky stuff with Laravel, Vue.js and Tailwind CSS.
Boris Lepikhin
Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.

Laravel Eloquent Scope as Select Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes an

Protone Media 75 Dec 7, 2022
Generate trends for your models. Easily generate charts or reports.

Laravel Trend Generate trends for your models. Easily generate charts or reports. Support us Like our work? You can support us by purchasing one of ou

Flowframe 139 Dec 27, 2022
This package lets you add uuid as primary key in your laravel applications

laravel-model-uuid A Laravel package to add uuid to models Table of contents Installation Configuration Model Uuid Publishing files / configurations I

salman zafar 10 May 17, 2022
🏭This package lets you create factory classes for your Laravel project.

Laravel Factories Reloaded ?? This package generates class-based model factories, which you can use instead of the ones provided by Laravel. Laravel 8

Christoph Rumpel 372 Dec 27, 2022
Laravel Larex lets you translate your whole Laravel application from a single CSV file.

Laravel Larex Translate Laravel Apps from a CSV File Laravel Larex lets you translate your whole Laravel application from a single CSV file. You can i

Luca Patera 68 Dec 12, 2022
This Laravel Nova tool lets you run artisan and bash commands directly from Nova 4 or higher.

Laravel Nova tool for running Artisan & Shell commands. This Nova tool lets you run artisan and bash commands directly from nova. This is an extended

Artem Stepanenko 17 Dec 15, 2022
A package to generate YouTube-like IDs for Eloquent models

Laravel Hashids This package provides a trait that will generate hashids when saving any Eloquent model. Hashids Hashids is a small package to generat

Λгi 25 Aug 31, 2022
This package allows you to easily work with NanoID in your Laravel models.

Laravel Model UUIDs Introduction Huge thanks to Micheal Dyrynda, whose work inspired me to create this package based on laravel-model-nanoid but uses

Parables Boltnoel 3 Jul 27, 2022
Viewi for Laravel: Build full-stack and completely reactive user interfaces with PHP.

[WIP] Laravel Viewi This is just a proof-of-concept. Don't use it in production! Viewi for Laravel: Build full-stack and completely reactive user inte

Protone Media 5 Jan 26, 2022
🏭 An easy way to generate populated factories for models.

Laravel Populated Factory provides an easy way to generate populated factories for models according to types & names of their columns. Install You can

Coderello 241 Nov 25, 2022
Generate previous attributes when saving Eloquent models

This package provides a trait that will generate previous attributes when saving any Eloquent model.

Ricardo Sawir 33 Nov 6, 2022
A collection of tools for rapidly building beautiful TALL stack interfaces, designed for humans.

Filament is a collection of tools for rapidly building beautiful TALL stack interfaces, designed for humans. Packages Admin Panel • Documentation • De

Filament 5.4k Jan 4, 2023
A toolkit for developing universal web interfaces with support for multiple CSS frameworks.

PHP UI Kit A toolkit for developing universal web interfaces with support for multiple CSS frameworks. Documentation Use cases One of the use cases is

Róbert Kelčák 6 Nov 8, 2022
Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Jameson Lopp 28 Dec 19, 2022
This Package helps you in laravel application to log all desired activity for each request from request entry point to generate response at a single snapshot.

Laravel Scenario Logger This Package helps you in laravel application to log all desired activity for each request from request entry point to generat

Mehrdad Mahdian 6 Sep 27, 2021
A Laravel package making a diagram of your models, relations and the ability to build them with it

Laravel Schematics This package allows you to make multiple diagrams of your Eloquent models and their relations. It will help building them providing

Maarten Tolhuijs 1.4k Dec 31, 2022
Kalibrant - a package that provides a simple way to manage your models settings

Introduction For your laravel 9.x applications, Kalibrant is a package that provides a simple way to manage your models settings. It is a simple way t

Starfolk 3 Jun 18, 2022
If you are beginner in WordPress plugin development or if you want to develop your own store product plugin you use this plugin

hirwa-products-plugin If you are beginner in WordPress plugin development or if you want to develop your own store product plugin you use this plugin

NIYIBIZI HIRWA 1 Aug 23, 2022
Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel 5.

Laravel-Mediable Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel. Features Filesystem-driven appro

Plank Design 654 Dec 30, 2022