Laracademy Generators - is a tool set that helps speed up the development process of a Laravel application.

Related tags

Laravel generators
Overview

Laracademy Generators

Latest Stable Version Total Downloads Latest Unstable Version License

Laracademy Generators - is a tool set that helps speed up the development process of a Laravel application.

Author(s):

Requirements

  1. PHP 7.4+
  2. Laravel 6.*
  3. MySQL *

** For Laravel 5.* please use the version 1.5

Usage

Step 1: Install through Composer

composer require "laracademy/generators" --dev

Step 2: Artisan Command

Now that we have added the generator to our project the last thing to do is run Laravel's Arisan command

php artisan

You will see the following in the list

generate:modelfromtable

Commands

generate:modelfromtable

This command will read your database table and generate a model based on that table structure. The fillable fields, casts, dates and even namespacing will be filled in automatically.

You can use this command to generate a single table, multiple tables or all of your tables at once.

This command comes with a bunch of different options, please see below for each parameter

  • --table=
    • This parameter if filled in will generate a model for the given table
    • You can also pass in a list of tables using comma separated values
    • When omitted, all tables will generate a model
      • In this scenario you can optionally specify a whitelist/blacklist in config/modelfromtable.php
      • migrations table will be blacklisted by default
  • --connection=
    • By default, if omitted, the default connection found in config/database.php will be used
    • To specify a connection, first ensure that it exists in your config/database.php
  • --folder=
    • By default, all models are store in your app/ directory. If you wish to store them in another place you can provide the relative path from your base laravel application.
    • Alternatively, use a lambda in config/modelfromtable.php to dynamically specify folder path
  • --namespace=
    • By default, all models will have the namespace of App\Models
    • Alternatively, use a lambda in config/modelfromtable.php to dynamically specify namespace
  • --debug=[true|false (default)]
    • Shows some more information while running
  • --singular=[true|false (default)]
    • This will create a singular titled model, e.g. "Categories" -> "Category"
  • --overwrite=[true|false (default)]
    • Overwrite model file(s) if exists
  • --timestamps=[true|false (default)]
    • whether to timestamp or not

Examples (CLI)

Generating a single table

php artisan generate:modelfromtable --table=users

Generating a multiple tables

php artisan generate:modelfromtable --table=users,posts

Changing to another connection found in database.php

php artisan generate:modelfromtable --connection=spark

Changing the folder where to /app/Models

php artisan generate:modelfromtable --table=user --folder=app\Models

Configuration file for saving defaults, dynamic lambdas

A config file should be in your project's config folder (if not, you can easily create it). Through this, you can set defaults you commonly use to cut down on the input your command line call requires. Some fields, like namespace, accept a static value or, more powerfully, a lambda to generate dynamic values. Additional fields not available to the CLI are available in the config. See below.

Whitelist/Blacklist (config only)

Particularly large databases often have a number of tables that aren't meant to have models. These can easily be filtered through either the whitelist or blacklist (or both!). Laravel's "migrations" table is already included in the blacklist. One nice feature is that you can wildcard table names if that makes sense for your situation...

'blacklist' => ['migrations'];
'whitelist' => ['user_address', 'system_*'];

Filename, using lambda

Large databases sometimes use a pattern of prefixing for organization, which you can use to organize your model files through a lambda.

'filename' => fn(string $tableName) => Str::studly(Str::after($tableName, '_')),

In this example, 'system_user' would generate the filename 'User'. Note that this is also available through the CLI, but it probably doesn't make as much sense to set there.

Folder path, using lambda

Using the last example, you can also organize the folder path using the prefix...

'folder' => (function (string $tableName) {
    $prefix = Str::studly(Str::before($tableName, '_'));
    $path = app()->path('Models') . "/{$prefix}";

    if (!is_dir($path)) {
        mkdir($path);
    }

    return $path;
}),

In this example, 'system_user' would generate the folder path 'path/to/your/install/app/Models/System'

Namespace, using lambda

Using the last example, you would want to then generate a matching namespace to the file path

'namespace' => fn(string $folderpath) => 'App/Models' . Str::after($folderpath, app()->path('Models')),

Therefore the folder path 'path/to/your/install/app/Models/System' would generate the namespace 'App\Models\System'

Delimiter (config only)

By default array values are delimited with a simple comma, but a common preference is to delimit with a newline as well.

'delimiter' => ",\n" . str_repeat(' ', 8),

Result:

class SomeModel extends Model
{
    protected $fillable = [
        'SomeField',
        'AnotherField',
        'YetAnotherField'
    ];

License

ModelGen is open-sourced software licensed under the MIT license

Bug Reporting and Feature Requests

Please add as many details as possible regarding submission of issues and feature requests

Disclaimer

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Call to undefined function Laracademy\Generators\Commands\studly_case()

    Call to undefined function Laracademy\Generators\Commands\studly_case()

    PHP 7.3.4 Laravel: 6.2

    Error when calling: Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined function Laracademy\Generators\Commands\studly_case() at /var/www/html/vendor/laracademy/generators/src/Commands/ModelFromTableCommand.php:103 image

    opened by smskin 5
  • Generate an Uppercase first letter, singular name in Model from lower case plural name of a table.

    Generate an Uppercase first letter, singular name in Model from lower case plural name of a table.

    Hi all,

    1. I am beginner learner of Laravel. I tried to generate a model class from an existing table in mysql. The generator generates a Model with uppercase but not singular! .I tried to rename the file in IDE but it throws an error. My syntax is :php artisan generate:modelfromtable --table=jobs.
    2. what about if I want to get "Category" Model class if my table name is"categories" ?

    Thanks for help.

    opened by Redcode456123 3
  • Error Class 'Str' not found on  laravel 6.1

    Error Class 'Str' not found on laravel 6.1

    when i run "php artisan generate:modelfromtable --all" in laravel 6.1. I found error "Class 'Str' not found".

    Starting Model Generate Command

    Symfony\Component\Debug\Exception\FatalThrowableError : Class 'Str' not found

    at /var/www/html/lava2/vendor/laracademy/generators/src/Commands/ModelFromTableCommand.php:290 286| // folder 287| // first check for namespace 288| if(! $this->option('namespace')) { 289| // set the namespace to the folder

    290| $this->options['namespace'] = Str::studly($this->option('folder')); 291| } else { 292| // default namespace 293| $this->options['namespace'] = ($this->option('namespace')) ? str_replace('app', 'App', $this->option('namespace')) : 'App'; 294| // remove trailing slash if exists

    Exception trace:

    1 Laracademy\Generators\Commands\ModelFromTableCommand::getOptions() /var/www/html/lava2/vendor/laracademy/generators/src/Commands/ModelFromTableCommand.php:71

    2 Laracademy\Generators\Commands\ModelFromTableCommand::handle() /var/www/html/lava2/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:32

    Please use the argument -v to see more details. image

    opened by goldgeer 3
  • 'describe' error during generation

    'describe' error during generation

    Is this expected to be compatible with a sqlsrv connection?

    I'm using SQL Server as my primary database and receive the following error when trying to run a generate:modelfromtable command...

    PDOException::("SQLSTATE[HY000]: General error: 20018 Could not find stored procedure 'describe'. [20018]

    opened by NVV-WebManager 3
  • Duplicate Columns and unnecessary models generating

    Duplicate Columns and unnecessary models generating

    Hi Everyone,

    I have a project where I have used MySQL as database. The problem I am getting is that I am getting system oriented model such as AccessLogs. The models that are generated also has many repetitive column. I am pasting the image image

    also

    image

    opened by hassaanih 2
  • Arrow function usage breaks compatibility for PHP Version 7.3.33 users

    Arrow function usage breaks compatibility for PHP Version 7.3.33 users

    https://github.com/laracademy/generators/blob/a06e98d106afcf5f0f55860975a91c74cf4633ce/src/Commands/ModelFromTableCommand.php#L212

    This single instance use of php 7.4's arrow function in the aforementioned line breaks compatibility for php version 7.3.33 users.

    This is resolved by changing the aforementioned line to the following line: $padding = array_reduce(array_keys($types), function ($carry, $x) { return max($carry, strlen($x)); }, 0) + 15;

    Replacing fn($carry, $x) => max($carry, strlen($x)) with function ($carry, $x) { return max($carry, strlen($x)); } restores functionality.

    opened by zacglenn 2
  • Syntax error

    Syntax error

    Hi I have installed the library but I am getting this error:

    syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')' at vendor/laracademy/generators/src/Commands/ModelFromTableCommand.php:316

    LINE 316 :

    $padding = array_reduce(array_keys($types), fn($carry, $x) => max($carry, strlen($x)), 0) + 15;

    opened by breakdom 2
  • Command Dosent recognise the --all command

    Command Dosent recognise the --all command

    I entered this command php artisan generate:modelfromtable --all --folder=app/Models Starting Model Generate Command No --table specified or --all

    Yet it didn't find the --all command

    opened by ax3cubed 2
  • [Request]Creating folders when they don't exist

    [Request]Creating folders when they don't exist

    That package is great for what I'm trying to do (Data migration between 2 external Databases) It generates all the models from the 2 dbs, maybe it can create the folder if it does not exist and we specify it with the --folder flag ?

    opened by cyberhicham 2
  • Does it work with Postgresql?

    Does it work with Postgresql?

    When I run it with Postgresql Database, I get error:

    $ php artisan generate:modelfromtable
    Starting Model Generate Command
    
       Illuminate\Database\QueryException 
    
      SQLSTATE[42601]: Syntax error: 7 ERROR:  syntax error at or near "REGEXP"
    LINE 1: ..."INFORMATION_SCHEMA"."COLUMNS" where "TABLE_NAME" REGEXP $1 ...
                                                                 ^ (SQL: select "TABLE_NAME" as "name", "COLUMN_NAME" as "field", "COLUMN_TYPE" as "type", IF(COLUMN_KEY = 'PRI', 1, 0) as isPrimary from "INFORMATION_SCHEMA"."COLUMNS" where "TABLE_NAME" REGEXP ()$ and "TABLE_NAME" NOT REGEXP (migrations)$ and "TABLE_SCHEMA" not in (information_schema, mysql, sys) order by "TABLE_NAME" asc, "isPrimary" desc)
    
      at vendor/laravel/framework/src/Illuminate/Database/Connection.php:703
        699▕         // If an exception occurs when attempting to run a query, we'll format the error
        700▕         // message to include the bindings with SQL, which will make this exception a
        701▕         // lot more helpful to the developer instead of just the database's errors.
        702▕         catch (Exception $e) {
      ➜ 703▕             throw new QueryException(
        704▕                 $query, $this->prepareBindings($bindings), $e
        705▕             );
        706▕         }
        707▕     }
    
          +24 vendor frames 
      25  artisan:37
          Illuminate\Foundation\Console\Kernel::handle()
    
    opened by Inkognitoo 1
  • speed optimizations

    speed optimizations

    • significant speed optimizations by querying all tables and columns in a schema in one shot, rather than on a per-table basis. in my case, querying ~175 tables, it's about 40x faster. added $schema option to config file so people can query the correct schema, but if that's not set i filter default system schemas so most users don't even need to set this.
    • a nice bonus of this is i'm able to get the primary key from mysql at the same time, so i deprecated the $primaryKey option entirely (particularly nice for legacy databases like mine where i previously had to use a lambda to query each table's primary key because they're all weird). this much better addresses issue #48. not a breaking change.
    • added a script execution timer
    opened by daverogers 1
  • unexpected '=>' (T_DOUBLE_ARROW), expecting ')' fn

    unexpected '=>' (T_DOUBLE_ARROW), expecting ')' fn

    solve by going to the file directory and change the fn to this here:

    $padding = array_reduce(array_keys($types), function($carry, $x){ return max($carry, strlen($x)); }, 0) + 15;

    opened by AlefMac 1
  • Duplicate, Triplicate columns from table when multiple copies of DB on server, different names

    Duplicate, Triplicate columns from table when multiple copies of DB on server, different names

    Have not used this for awhile, but using it again and I get an error when I execute something like this.

    php artisan generate:modelfromtable --connection=mysql2 --table=orders --folder=app/Models/UIData --debug=true

    where the mysql2 connection specifies a specific DB on my server. That isn't null. However, there are 3 copies of my DB on the server: RIS, RISDEV, and RISINIT, which are basically production, development and a blank DB, so I have 3 orders tables on the server, but only one in the RISDEV db.

    When I execute the command above I get:

    • @property int $id
    • @property int $id
    • @property int $id . . . .

    It basically has 3 copies of each property / column from the server (i.e. all 3 DB's)

    Starting Model Generate Command loading model stub Retrieving database tables Generating file: Orders.php Writing model: /nginx-home/Migration/app/Models/UIData/Orders.php Completed in 0.28 seconds

    php artisan generate:modelfromtable --connection=mysql2 --table=RISDEV.orders --folder=app/Models/UIData --debug=true

    Starting Model Generate Command loading model stub Retrieving database tables Completed in 0.19 seconds

    does not do anything as far as creating a model.

    My config for the DB is. Is there a way to more specifically specify the DB on the server to use since it seems to be reading tables at the server level rather that at the DB level.

        'mysql2' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_SECOND', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],
    
    opened by sscotti 1
  • primary key column name not detected

    primary key column name not detected

    Primary key in model is the Laravel default, while in the table is different.

    Table foos primary key: id_foo

    Model generated from table foos: protected $primaryKey = 'id';

    Expected in model: protected $primaryKey = 'id_foo';

    opened by GabrieleMartini 2
  • unable to set which database use as default database name is appended automaticaly,

    unable to set which database use as default database name is appended automaticaly,

    Hello,

    I've got one mysql user that can access various databases on the same server I'm trying toe generate model but it. doesn't works. because your script append the default database name.

    php artisan generate:modelfromtable --table=dbx.users--folder=app\Models
    
    SQLSTATE[42S02]: Base table or view not found: 1146 Table 'websockets.dbx.users' doesn't exist
    

    ¿Can you fix it ?

    Regards

    opened by scramatte 4
  •  syntax error at or near

    syntax error at or near "describe"

    Using Postgresql:

    vagrant@homestead:~/Code/foobar$ php artisan generate:modelfromtable --table=archetypes
    Starting Model Generate Command
    
    
      [Illuminate\Database\QueryException]
      SQLSTATE[42601]: Syntax error: 7 ERROR:  syntax error at or near "describe"
      LINE 1: describe archetypes
              ^ (SQL: describe archetypes)
    
    
    
      [PDOException]
      SQLSTATE[42601]: Syntax error: 7 ERROR:  syntax error at or near "describe"
      LINE 1: describe archetypes
              ^
    
    opened by Jaspur 6
Releases(3.6)
Owner
Laracademy
Laracademy
A collection of generators for Lumen and Laravel 5.

Lumen generators A collection of generators for Lumen and Laravel 5. Contents Why ? Installation Quick Usage Detailed Usage Model Generator Migration

Amine Ben hammou 349 Mar 24, 2022
Generate form validators for Laravel: an extension of way/generators

Laravel Form Validator Contents Introduction Installation Usage Example Tests Introduction After using Jeffrey Way's Generator and his Validator packa

John Evans 6 Jan 14, 2022
Laravel File Generators with config and publishable stubs

Laravel File Generators Custom Laravel File Generators with a config file and publishable stubs. You can publish the stubs. You can add your own stubs

Ben-Piet O'Callaghan 116 Oct 29, 2022
Laravel-OvalFi helps you Set up, test, and manage your OvalFi integration directly in your Laravel App.

OvalFi Laravel Package Laravel-OvalFi helps you Set up, test, and manage your OvalFi integration directly in your Laravel App. Installation You can in

Paul Adams 2 Sep 8, 2022
Convenient tool for speeding up the intern/officer review process.

icpc-app-screen Convenient tool for speeding up the intern/officer applicant review process. Eliminates the pain from reading application responses of

null 1 Oct 30, 2021
A Laravel package to speed up deployment by skipping asset compilation whenever possible.

Airdrop for Laravel Read the full docs at hammerstone.dev/airdrop/docs. Hammerstone Airdrop for Laravel is a package that speeds up your deploys by sk

Hammerstone 160 Nov 24, 2022
A package for simplifying the integration of a maker-checker approval process to your Laravel application.

prismaticoder/maker-checker-laravel The prismaticoder/maker-checker-laravel package is a comprehensive Laravel package that provides a flexible and cu

Jesutomiwa Salam 12 Jun 16, 2023
Flysystem storage with local metadata storage for speed and manageability.

Laravel Filer This project was started to scratch my itch on our growing Laravel site: Metadata for all files is stored in a local repository - Suppor

Nick Vahalik 16 May 23, 2022
Livewire trait (throttling). Limiting request processing speed

Livewire Throttling Installation You can install the package via composer: composer require f1uder/livewire-throttling Usage Livewire component <?php

Fluder 5 Dec 7, 2022
This tool gives you the ability to set the default collapse state for Nova 4.0 menu items.

Nova Menu Collapsed This tool gives you the ability to set the default collapse state for Nova 4.0 menu items. Requirements php: >=8.0 laravel/nova: ^

Artem Stepanenko 10 Nov 17, 2022
Keyword Generator Tool helps you discover keyword opportunities related to your query input.

This plugin simply helps you discover keyword opportunities related to your query input. Installation Download the zip file of the repository or clone

WP Refers 1 May 3, 2022
A laravel package to handle sanitize process of model data to create/update model records.

Laravel Model UUID A simple package to sanitize model data to create/update table records. Installation Require the package using composer: composer r

null 66 Sep 19, 2022
A Laravel package helps you add a complete real-time messaging system to your new / existing application with only one command.

A Laravel package helps you add a complete real-time messaging system to your new / existing application with only one command.

Munaf Aqeel Mahdi 1.7k Jan 5, 2023
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
Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Ogundiran Adewale Charles 2 Jul 27, 2022
Taskpm - Run multi tasks by PHP multi process

php-pkg-template Run multi tasks by PHP multi process Install composer composer require phppkg/taskpm Usage github: use the template for quick create

PHPPkg 2 Dec 20, 2021
Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster.

Laravel Kickstart What is Laravel Kickstart? Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster. It com

Sam Rapaport 46 Oct 1, 2022
A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic

A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic! concepts like , Hijri Dates & Arabic strings and so on ..

Adnane Kadri 49 Jun 22, 2022
A set of useful Laravel collection macros

A set of useful Laravel collection macros This repository contains some useful collection macros. Spatie is a webdesign agency based in Antwerp, Belgi

Spatie 1.5k Dec 31, 2022