Coder Social home page Coder Social logo

generators's Introduction

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.

generators's People

Contributors

amphetkid avatar cyberhicham avatar danrovito avatar daverogers avatar johnneijzen avatar michael-mcmullen avatar mindspread avatar mrbig00 avatar mrzainulabideen avatar osamamohammed avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

generators's Issues

laracademy/generators 2.0 empty namespace

Hello.

I am using laravel 6.1.0 & laracademy/generators 2.0

This command is not problem.
image

But when i open model by made generator, i could see it.
image

There is empty after namespace. Sure, this makes error.
If i add App after namespace like this. There is no error.

namespace App;

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()

Laravel 8 Models

Update to work with Laravel 8 Model Namespace Change (default)

[Request] Disabling Timestamps

Hello,

The usecase for me with that package is when manipulating other databases (not laravel based ones) so I'd be happy to have this :

    /**
     * Disabling Auto Timestamps.
     *
     * @var boolean
     */
    public $timestamps = false;

I'll try to make a PR when I got some spare time :)

Singular

As database table names are plural when you migrate from laravel if the name is singular so the generator should also convert plural to singular while creating a class name which is at

ModelFromTableCommand.php line 101

just a suggestion

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;

$dates-cast multiplied if used on multiple tables

If only one table is used as source for a new model everything works as expected.
When used with "--table=table1,table2,table3,table4" and the migrations use the SoftDeletes trait the "deleted_at"-column gets added to the $dates-array one more time for each processed table.

Details for the example above:
Table1.php: "protected $dates = ['deleted_at'];
Table2.php: "protected $dates = ['deleted_at', 'deleted_at'];
Table3.php: "protected $dates = ['deleted_at', 'deleted_at', 'deleted_at'];
Table4.php: "protected $dates = ['deleted_at', 'deleted_at', 'deleted_at', 'deleted_at'];

command --all not working on laravel 8

i write php artisan generate:modelfromtable --table=clients it works but if try php artisan generate:modelfromtable --all it gives
No --table specified or --all
image

'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]

When a table name is a sql keyword, the model is not generated

When the table name is groups, the command simply throws out a SQL error.

Here is the error:

Exception trace:

1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'groups' at line 1")

Satisfied, but still room to improvement

Currently, I am satisfied with the approach. But we are using smarter IDEs for development, and I need still to add model properties to the doc block for the type hinting while assigning or accessing model attributes as:

     @property string    $created_at
     @property Date      $updated_at
     @property DateTime  $deleted_at

with in the model class. If it is possible and easy to go, please add this feature with in class doc block.
Still searching for fair model generation modules as Yii has.
PS: I am using PHPStrom.

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

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
          ^

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

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

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:

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'),
        ]) : [],
    ],

Changing the folder

Hi!

  1. The documentation says to try the below to change the folder, it doesn't work

php artisan generate:modelfromtable --table=user --folder=app\Models
What one gets is a folder named appModel

This is what works :

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

  1. After generating the folder in the right manner, the changes is not effected in the namespace so irrespective of the fact the structure is now App\Models\User.php, namespace still remains namespace App

Table with underscore

If you have a table with an underscore in it: user_post for example. A model with the name 'User_post' is generated instead of the expected UserPost.

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';

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

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.

[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 ?

Arrow function usage breaks compatibility for PHP Version 7.3.33 users

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

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.