Giter Site home page Giter Site logo

laracasts / laravel-5-generators-extended Goto Github PK

View Code? Open in Web Editor NEW
2.4K 87.0 348.0 138 KB

This package extends the core file generators that are included with Laravel 5

Home Page: https://laracasts.com/lessons/faster-workflow-with-generators

License: MIT License

PHP 100.00%

laravel-5-generators-extended's Introduction

Extended Migration Generators for Laravel 6, 7, 8 and 9

Easily define the migration schema right in your make:migration command. The new commands this package provides are:

  • make:migration:schema
  • make:migration:pivot

Which allows you to do php artisan make:migration:schema create_dogs_table --schema="name:string:nullable, description:text, age:integer, email:string:unique" and get a full migration that you can run using php artisan migrate. For simple cases like this one, no need to tinker inside the migration file itself. And if you do need to change anything, it's easier because the bulk of the code has already been generated.

Created in 2015 by Jeffrey Way as a natural progression of his JeffreyWay/Laravel-4-Generators package, to provide the same features for Laravel 5. Since 2017 it's been maintained by the Backpack for Laravel team, with features and fixes added by community members like you. So feel free to pitch in.

https://user-images.githubusercontent.com/1032474/92732702-cd8b3700-f344-11ea-8e3b-ae86501d66fe.gif

Table of Contents

Versions

Depending on your Laravel version, you should:

Installation

You can install v2 of this project using composer, the service provider will be automatically loaded by Laravel itself:

composer require --dev laracasts/generators

You're all set. Run php artisan from the console, and you'll see the new commands in the make:* namespace section.

Examples

Migrations With Schema

php artisan make:migration:schema create_users_table --schema="username:string, email:string:unique"

Notice the format that we use, when declaring any applicable schema: a comma-separated list...

COLUMN_NAME:COLUMN_TYPE

So any of these will do:

username:string
body:text
age:integer
published_at:date
excerpt:text:nullable
email:string:unique:default('[email protected]')

Using the schema from earlier...

--schema="username:string, email:string:unique"

...this will give you:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('users', function(Blueprint $table) {
			$table->increments('id');
			$table->string('username');
			$table->string('email')->unique();
			$table->timestamps();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('users');
	}

}

When generating migrations with schema, the name of your migration (like, "create_users_table") matters. We use it to figure out what you're trying to accomplish. In this case, we began with the "create" keyword, which signals that we want to create a new table.

Alternatively, we can use the "remove" or "add" keywords, and the generated boilerplate will adapt, as needed. Let's create a migration to remove a column.

php artisan make:migration:schema remove_user_id_from_posts_table --schema="user_id:integer"

Now, notice that we're using the correct Schema methods.

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class RemoveUserIdFromPostsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('posts', function(Blueprint $table) {
			$table->dropColumn('user_id');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('posts', function(Blueprint $table) {
			$table->integer('user_id');
		});
	}

}

Here's a few other examples of commands that you might write:

  • php artisan make:migration:schema create_posts_table
  • php artisan make:migration:schema create_posts_table --schema="title:string, body:text, excerpt:string:nullable"
  • php artisan make:migration:schema remove_excerpt_from_posts_table --schema="excerpt:string:nullable"

Models

Now, when you create a migration, you typically want a model to go with it, right? By default, this package won't create a model to go with the migration. But it could. Just specify --model=true and it will do that for you:

php artisan make:migration:schema create_dogs_table --schema="name:string" --model=true

Migration Path

If you wish to specify a different path for your migration file, you can use the --path option like so:

php artisan make:migration:schema create_dogs_table --path=\database\migrations\pets

Foreign Constraints

There's also a secret bit of sugar for when you need to generate foreign constraints. Imagine that you have a posts table, where each post belongs to a user. Let's try:

php artisan make:migration:schema create_posts_table --schema="user_id:unsignedInteger:foreign, title:string, body:text"

Notice that "foreign" option (user_id:unsignedInteger:foreign)? That's special. It signals that user_id should receive a foreign constraint. Following conventions, this will give us:

$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');

As such, for that full command, our schema should look like so:

Schema::create('posts', function(Blueprint $table) {
	$table->increments('id');
	$table->unsignedInteger('user_id');
	$table->foreign('user_id')->references('id')->on('users');
	$table->string('title');
	$table->text('body');
	$table->timestamps();
);

Neato.

Pivot Tables

So you need a migration to setup a pivot table in your database? Easy. We can scaffold the whole class with a single command.

php artisan make:migration:pivot tags posts

Here we pass, in any order, the names of the two tables that we need a joining/pivot table for. This will give you:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostTagPivotTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('post_tag', function(Blueprint $table) {
			$table->integer('post_id')->unsigned()->index();
			$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
			$table->integer('tag_id')->unsigned()->index();
			$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('post_tag');
	}

}

Notice that the naming conventions are being followed here, regardless of what order you pass the table names.

laravel-5-generators-extended's People

Contributors

93gaurav93 avatar arifmahmudrana avatar atorscho avatar bogdankharchenko avatar brandonsurowiec avatar casperlaitw avatar codeatbusiness avatar espadav8 avatar fredodev avatar hiendv avatar jeffreyway avatar jpuck avatar jtyms avatar naneri avatar otherpaco avatar ozankurt avatar panstromek avatar pxpm avatar ranzix avatar rap2hpoutre avatar stamp avatar sunspikes avatar tabacitu avatar thomasjones4 avatar vinaydotblog 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  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

laravel-5-generators-extended's Issues

Identifier name 'long_table_names_blah_id' is too long

Getting this error:
[PDOException] SQLSTATE[42000]: Syntax error or access violation: 1059 Identifier name 'snow_lesson_category_snow_mo nitor_snow_lesson_category_id_foreign' is too long

With this migration (or with any migration with long table names):
php artisan make:migration:pivot snow_monitors snow_lesson_categories

Can be solved by providing your own shorter key name.

$table->foreign('snow_lesson_category_id', 'snow_lesson_category_foreign')->references('id')->on('snow_lesson_categories')->onDelete('cascade');

This also happened with my primary key.

->unsigned() missing

When adding a relation with the generator, it generates for example:

            $table->integer('user_id');
            $table->foreign('user_id')->references('id')->on('users');

But then ->unsigned(); is missing on the integer itself.

make:seed curly class

While creating seed with make:seed this happens


use Illuminate\Database\Seeder;

// composer require laracasts/testdummy
use Laracasts\TestDummy\Factory as TestDummy;

class {{class}} extends Seeder//
{
    public function run()
    {
        // TestDummy::times(20)->create('App\Post');
    }
}

adding {{class}} not substituting classname

model=false flag not working

I've created my migration using the following command,
Even the flag is set a Model 'EncuentrosTarjeta.php' is created under "app" folder:

php artisan make:migration:schema create_encuentros_tarjetas_table --schema="encuentro_id:integer:unsigned:foreign" --model=false

make:migration:schema model is empty

hi,

I tried running the following command:
hp artisan make:migration:schema create_clubs_table --schema="name:string, email:string, abbreviation:string:nullable"

And this created the right migration, but the model file it created was empty:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Club extends Model {

    //

}

I don't know if this is intended or not, but just wanting to point this out :)

Cannot add foreign key constraint (mysql)

When creating a schema which includes a foreign key, if you forget to add the "unsigned" option to the key, you will get a mysql error when you try to run the migration.

For instance, the README has an example regarding foreign keys, but before we use it, we need to setup the users table, so I'll do a dumb one here:

php artisan make:migration:schema create_users_table --schema="fullname:string"

This generates:

Schema::create('users', function(Blueprint $table) {
    $table->increments('id');
    $table->string('fullname');
    $table->timestamps();
);

Fine and dandy. (Note, the "increments" above creates an unsigned integer field in mysql. This is important).

So, now we move on to the example given in the docs for making a schema which relates to this new users table...

php artisan make:migration:schema create_posts_table --schema="user_id:integer:foreign, title:string, body:text"

Which generates the following:

Schema::create('posts', function(Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->foreign('user_id')->references('id')->on('users');
    $table->string('title');
    $table->text('body');
    $table->timestamps();
);

Running this migration, you will find it will bark at you saying

General error: 1215 Cannot add foreign key constraint"

To solve the problem on the fly, just go into the create_posts_table migration file and change one line:

// $table->integer('user_id');
$table->integer('user_id')->unsigned();

Since I've not done a PR before, and don't have the time at this very moment to learn, I'll leave this up to someone else to do unless (a) it's not fixed quickly, (b) I get annoyed enough by it and (c) I get the time to learn how to do PRs. :)

Hopefully this is helpful and will spark a change.

Cheers.

when a pivot table is created, it gives wrong class name

hello Jeffery
having used this generator to create a pivot table, it did everything correct except that it gave:
class {{class}} extends Migration as the header with classname not being specified, perhaps it didn't replace the variable, perhaps it's a setup problem here but everything else is working fine.

Thanks

Pivot doesn't render the class name

The output migration seems fine except for the class declaration, it doesn't replace the class name and this is the output:

class {{class}} extends Migration

The command was run like this: (The README didn't said you need to specify a class name, just the 2 table names)

$ php artisan make:migration:pivot users stores

Dev dependency on composer.json

"laracasts/generators": "^1.1",

seed stub not parsing {{class}} with seed name

Hi,

Small issue: running a simple php artisan make:seed users results in no errors, but the output of UsersTableSeeder.php :

    use Illuminate\Database\Seeder;

    // composer require laracasts/testdummy
    use Laracasts\TestDummy\Factory as TestDummy;

    class {{class}} extends Seeder
    {
        public function run()
        {
            // TestDummy::times(20)->create('App\Post');
        }
    }

make:migration:schema generates foreign constraints incorrectly

command

php artisan make:migration:schema create_posts_table --schema="user_id:integer:foreign"

generates

// ...
$table->increments('id');
$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
// ...

expected output

// ...
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
// ...

since most probably foreign keys will be used with $table->increments('id'); on other side

Version constraint error when installing

Hi, I've tried installing this using the composer command you provided and I get these errors:
[RuntimeException] Could not load package dragonrun1/phpspec in http://packagist.org: [Unexpec tedValueException] Could not parse version constraint ^1.0.1: Invalid versi on string "^1.0.1"
[UnexpectedValueException] Could not parse version constraint ^1.0.1: Invalid version string "^1.0.1"
My composer.json already seems to contain "phpspec/phpspec": "~2.1", out of the box on L5, so could there be some kind of conflict between the two?

Any help on this would be great!

missing documentation -- defining new column length

Hello, If i want to add a new column with migrations something like:

make:migration:schema add_password_to_users_table --schema="password:varchar"

how do I specify the field length? just looking for a reference sheet for the syntax. thanks

Generate function with Artisan !!?

Hi everyone,
I'm looking for a way to generate code function(php ) from dashboard with laravel or just with php !!! Any help will be great :)

or a way to generate function with artisan !
Thanks in advance

Generators not showing

I followed the steps as listed in the readme.md but the generators are not showing when I run php artisan

When I add the service provider to config/app.php, they do show ?

Is an index necessary on a foreign key column?

Maybe not exactly the right place to ask this question.. but I was wondering about the pivot table stub: is it really necessary to put ->index() on the foreign key fields? I thought that foreign key fields are always indexed automatically.

Creating Migrations From a Controller

Any suggestions on creating migrations from a controller?

When running

Artisan::call('make:migration:schema', ['name' => 'create_test_table', '--schema' => 'username:string, email:string:unique']);

no migration is created.

Installation : USAGE step2 => return me an error :

[Symfony\Component\Debug\Exception\FatalErrorException]
syntax error, unexpected end of file, expecting function (T_FUNCTION)

I've install this under the app.php and it's ok when I do a php artisan !

Lumen support?

Yo,

Will this work with Lumen? I'm not seeing any make commends in term

Thanks ~

Improvements for Pivot Tables

In my opinion a Pivot requires the $table->timestamps(); fields to support the ->withTimestamps(); function.
Also i would prefer an id field as primary key (First normal form).

Additionally a combined index between the relational id's would be a benefit for performance.

Correct me if I'm wrong

how can i use `generate:resource`

In the previous repository there was an option to use the following command. can you please tell me is there any way to this in this extended generator?
php artisan generate:resource

generate:scaffold not working at all

php artisan generate:scaffold not working at all. Its throwing error after:$ php artisan generate:scaffold {resource}

Do you want me to create a {resource} model? [yes|no] yes

[InvalidArgumentException] The "--templatePath" option requires a value.

But in the list of options after executing php artisan generate:scaffold --help there is no --templatePath And again if I try with php artisan generate:scaffold {resource} --templatePath

[RuntimeException]
The "--templatePath" option does not exist.

Pivot doesn't substitute class name.

Command:

$ ./artisan make:migration:pivot somethings otherthings
Migration created successfully.

Generates:

integer('otherthing_id')->unsigned()->index(); $table->foreign('otherthing_id')->references('id')->on('otherthings')->onDelete('cascade'); $table->integer('something_id')->unsigned()->index(); $table->foreign('something_id')->references('id')->on('somethings')->onDelete('cascade'); }); } ``` /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('otherthing_something'); } ``` }

2 migrations files are generated on php artisan make:migration:schema.

php artisan make:migration:schema create_companies_table - schema="user_id:integer:foreign:unsign
ption:text,active:boolean,tax_no:varchar,child:boolean,child_of:integer:unsign"

This command generate two files ,

2015_05_13_084536_create_companies_table

public function up()
{
    Schema::create('companies', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('title');
        $table->text('description');
        $table->boolean('active');
        $table->varchar('tax_no');
        $table->boolean('child');
        $table->intger('child_of')->unsign();
        $table->timestamps();
    });
}

2015_05_13_084537_create_companies_table

public function up()
{
    Schema::create('companies', function(Blueprint $table)
    {
        $table->increments('id');
        $table->timestamps();
    });
}

And in autoload class it register first migration file.
'CreateCompaniesTable' => $baseDir . '/database/migrations/2015_05_13_084536_create_companies_table.php',

Generating pivots with tables that contain underscores in name produces incorrect class name

Hello!

I've had a go at running this:


 php artisan make:migration:pivot test_table foo_table

and the generated migration had a class name of CreateBar_tableFoo_tablePivotTable.

I'm running on Laravel 5 and pulled in (as per instructions) generators using:


 composer require laracasts/generators --dev

This created


"laracasts/generators": "^1.1"


in my composer.json

Thanks!

Tom

ambiguous class name

bug:
if a table name has an underscore , then the class name created in the migration for that table also includes an unexpected underscore.

e.g
php artisan migration:make:pivot locality time_slot
results in creation of piviot table create_locality_time_slot_pivot_table
as:
class CreateLocalityTime_slotPivotTable extends Migration
{ public function up()
{
Schema::create('locality_time_slot', function(Blueprint $table) {
$table->integer('locality_id')->unsigned()->index();
$table->foreign('locality_id')->references('id')->on('localities')->onDelete('cascade');

....}}

Use --schema option with make:model:schema

Maybe this is in the works already? If not would it be possible to fill the migration when using make:model:schemalike so:

php artisan make:model:schema Participant --schema="firstname:string, name:string, email:string, position:string:nullable, training_id:integer:unsigned, user_id:integer:unsigned"

Proposal: Suggest laracasts/TestDummy in composer.json

I created my first seed files in Laravel yesterday. The code I wrote to seed the database would have been way easier if I remembered about your laracasts/TestDummy package. I propose you add it as a suggested package in composer.json. That would have really helped me.

Let me know what you think.

Command make:view?

there are plans to implement the make:view command like generate:view was on way/generators package?

Adding a foreign column causes duplicate dropColumn

When creating a scheme with a foreign key the migration has a duplicated dropColumn line, e.g. after running this command php artisan make:migration:schema add_phone_to_users_table --schema="phone:integer:unsigned:foreign" the following migration is created

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddPhoneToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function(Blueprint $table) {
            $table->integer('phone')->unsigned();
            $table->foreign('phone')->references('id')->on('phones');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function(Blueprint $table) {
            $table->dropColumn('phone');
            $table->dropColumn('phone');
        });
    }
}

Foreign keys

when using

"user_id:integer:foreign"

the unsigned flag needs to be added to the user_id field before the foreign_key column

e.g. this needs to create

$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');

instead of

$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users');

(php artisan) Causes an Error in Laravel 5.2

Can anyone help, I am getting an error when I run php artisan

  [ReflectionException]                                
  Class Illuminate\Foundation\Composer does not exist 

had to remove this line to get php artisan to work

    if ($this->app->environment() == 'local') {
        $this->app->register('Laracasts\Generators\GeneratorsServiceProvider');
    }

Running artisan fresh after installing this package, will unregister it.

Not an "issue" but a warning. If you follow the instructions and add the provider to app/Providers/AppServiceProvider.php, upon running artisan fresh, you will have to re-add the provider as artisan fresh clears that out.

Also - if there's a better place to add comments like this, please advise me of where. :)

I got this strange behaviour when generating the migrations.

If you run the generator command without putting a space after each of the coma separated list of the schema fields like this:
php artisan make:migration:schema create_employees_table --schema="first_name:string,last_name:string"

the generated migration file will be: $table->string,last_name('first_name')->string() which is not right.

Where as you add the space after the comma you will get the correct migration file like so:
$table->string('first_name');
$table->string('last_name');

I think there is a small bug in there.

Thanks.

error

I'm getting this error:

The requested package laracasts/generators could not be found....I'm using Laravel 5.

Pivot not working correctly

When generating pivot table, the generator is putting ->unsigned() before >index() and is causing the index not to be created at the right time (I'm guessing) and causes a failure on creating the foreign keys. If I reorder and put the ->index() method first in the change, it creates the index and foreign keys

Pivot generator sometimes sorts columns wrong

In edge cases like when two table names overlap, the pivot generator will sort them wrong.

For example: Two tables, students and studentgroups will be sorted as studentgroup_student instead of student_studentgroup.

Suggested fix:
In PivotMigrationMakeCommand.php make sure to re-sort table names after applying str_singular on them.

I would submit a patch but I'm new to git and github, so sorry :/

unexpected '{' while creating Pivot

I try to create a pivot:

php artisan make:migration:pivot campaigns campaignresponses

The migration file is created but when I run

php artisan migrate

I get

[Symfony\Component\Debug\Exception\FatalErrorException]        
syntax error, unexpected '{', expecting identifier (T_STRING)

What happend is that in migration file in line 6 the class name was not created an left as is

class {{class}} extends Migration

error when require the package

when i put this command

composer require 'laracasts/generators' --dev

i have this error

[InvalidArgumentException]
Could not find package 'laracasts/generators' at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

what's the problem ? thank you

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.