Coder Social home page Coder Social logo

laravel-4-generators's Introduction

Fast Workflow in Laravel With Custom Generators

Build Status

This Laravel package provides a variety of generators to speed up your development process. These generators include:

  • generate:model
  • generate:view
  • generate:controller
  • generate:seed
  • generate:migration
  • generate:pivot
  • generate:resource
  • generate:scaffold

Installation

Want a 5-minute video overview?

Laravel 5

If you're using Laravel 5, then use this package instead.

Laravel 4.2 and Below

Begin by installing this package through Composer. Edit your project's composer.json file to require way/generators.

"require-dev": {
	"way/generators": "~2.0"
}

Next, update Composer from the Terminal:

composer update --dev

Once this operation completes, the final step is to add the service provider. Open config/app.php, and add a new item to the providers array.

'Way\Generators\GeneratorsServiceProvider'

That's it! You're all set to go. Run the artisan command from the Terminal to see the new generate commands.

php artisan

Usage

Think of generators as an easy way to speed up your workflow. Rather than opening the models directory, creating a new file, saving it, and adding the class, you can simply run a single generate command.

Migrations

Laravel offers a migration generator, but it stops just short of creating the schema (or the fields for the table). Let's review a couple examples, using generate:migration.

php artisan generate:migration create_posts_table

If we don't specify the fields option, the following file will be created within app/database/migrations.

<?php

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

class CreatePostsTable extends Migration {

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

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

}

Notice that the generator is smart enough to detect that you're trying to create a table. When naming your migrations, make them as descriptive as possible. The migration generator will detect the first word in your migration name and do its best to determine how to proceed. As such, for create_posts_table, the keyword is "create," which means that we should prepare the necessary schema to create a table.

If you instead use a migration name along the lines of add_user_id_to_posts_table, in that case, the keyword is "add," signaling that we intend to add rows to an existing table. Let's see what that generates.

php artisan generate:migration add_user_id_to_posts_table

This will prepare the following boilerplate:

<?php

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

class AddUserIdToPostsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::table('posts', function(Blueprint $table) {

        });
	}


	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
	    Schema::table('posts', function(Blueprint $table) {

        });
	}

}

Notice how, this time, we're not doing Schema::create.

Keywords

When writing migration names, use the following keywords to provide hints for the generator.

  • create or make (create_users_table)
  • add or insert (add_user_id_to_posts_table)
  • remove (remove_user_id_from_posts_table)
  • delete or drop (delete_users_table)

Generating Schema

This is pretty nice, but let's take things a step further and also generate the schema, using the fields option.

php artisan generate:migration create_posts_table --fields="title:string, body:text"

Before we decipher this new option, let's see the output:

<?php

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

class CreatePostsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::create('posts', function(Blueprint $table) {
            $table->increments('id');
            $table->string('title');
			$table->text('body');
			$table->timestamps();
        });
	}

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

}

Nice! A few things to notice here:

  • The generator will automatically set the id as the primary key.
  • It parsed the fields options, and added those fields.
  • The drop method is smart enough to realize that, in reverse, the table should be dropped entirely.

To declare fields, use a comma+space-separated list of key:value:option sets, where key is the name of the field, value is the column type, and option is a way to specify indexes and such, like unique or nullable. Here are some examples:

  • --fields="first:string, last:string"
  • --fields="age:integer, yob:date"
  • --fields="username:string:unique, age:integer:nullable"
  • --fields="name:string:default('John Doe'), bio:text:nullable"
  • --fields="username:string(30):unique, age:integer:nullable:default(18)"

Please make note of the last example, where we specify a character limit: string(30). This will produce $table->string('username', 30)->unique();

It is possible to destroy the table by issuing:

php artisan generate:migration delete_posts_table

As a final demonstration, let's run a migration to remove the completed field from a tasks table.

php artisan generate:migration remove_completed_from_tasks_table --fields="completed:boolean"

This time, as we're using the "remove" keyword, the generator understands that it should drop a column, and add it back in the down() method.

<?php

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

class RemoveCompletedFromTasksTable extends Migration {

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


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

}

Models

php artisan generate:model Post

This will create the file, app/models/Post.php and insert the following boilerplate:

<?php

class Post extends \Eloquent {

}

Views

The view generator is fairly simple.

php artisan generate:view admin.reports.index

This command will create an empty view, /app/views/admin/reports/index.blade.php. If the provided directory tree does not exist, it will be created for you.

Seeds

Laravel provides us with a flexible way to seed new tables.

php artisan generate:seed users

Set the argument to the name of the table that you'd like a seed file for. This will generate app/database/seeds/UsersTableSeeder.php and populate it with:

<?php

// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class UsersTableSeeder extends Seeder {

    public function run()
    {
        $faker = Faker::create();

        foreach(range(1, 10) as $index)
        {
            User::create([

            ]);
        }
    }

}

This will give you a basic bit of boilerplate, using the popular Faker library. This is a nice way to seed your DB tables. Don't forget to pull in Faker through Composer!

Pivot

When you require a new pivot table, the generate:pivot table expedites the process of creating the appropriate migration.

Simply pass the name of the two tables that require a joining pivot table. For orders and users, you might do:

php artisan generate:pivot orders users

This will create the following migration:

<?php

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

class CreateOrderUserTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::create('order_user', function(Blueprint $table) {
            $table->increments('id');
			$table->integer('order_id')->unsigned()->index();
			$table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
			$table->integer('user_id')->unsigned()->index();
			$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
			$table->timestamps();
        });
	}


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

}

Notice that it correctly sets the table name according to your two provided tables, in alphabetical order. Now, run php artisan migrate to create your pivot table!

Resources

The generate:resource command will do a number of things for you:

  • Generate a model
  • Generate index, show, create, and edit views
  • Generate a controller
  • Generate a migration with schema
  • Generate a table seeder
  • Migrate the database

When triggering this command, you'll be asked to confirm each of these actions. That way, you can tailor the generation to what you specifically require.

Example

Imagine that you need to build a way to display posts. While you could manually create a controller, create a model, create a migration and populate it with the schema, and then create a table seeder...why not let the generator do that?

php artisan generate:resource post --fields="title:string, body:text"

If you say yes to each confirmation, this single command will give you boilerplate for:

  • app/models/Post.php
  • app/controllers/PostsController.php
  • app/database/migrations/timestamp-create_posts_table.php (including the schema)
  • app/database/seeds/PostsTableSeeder.php

Scaffolding

The scaffolding generator is similar to generate:resource, except it will add some beginning boilerplate to these files, as a convenience.

For instance, when running generate:scaffold post, your controller boilerplate will be:

<?php

class PostsController extends \BaseController {

	/**
	 * Display a listing of posts
	 *
	 * @return Response
	 */
	public function index()
	{
	    $posts = Post::all();

	    return View::make('posts.index', compact('posts'));
	}

	/**
	 * Show the form for creating a new post
	 *
	 * @return Response
	 */
	public function create()
	{
        return View::make('posts.create');
	}

	/**
	 * Store a newly created post in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
	    $validator = Validator::make($data = Input::all(), Post::$rules);

	    if ($validator->fails())
	    {
	        return Redirect::back()->withErrors($validator)->withInput();
	    }

	    Post::create($data);

	    return Redirect::route('posts.index');
	}

	/**
	 * Display the specified post.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
	    $post = Post::findOrFail($id);

	    return View::make('posts.show', compact('post'));
	}

	/**
	 * Show the form for editing the specified post.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		$post = Post::find($id);

		return View::make('posts.edit', compact('post'));
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$post = Post::findOrFail($id);

		$validator = Validator::make($data = Input::all(), Post::$rules);

        if ($validator->fails())
        {
            return Redirect::back()->withErrors($validator)->withInput();
        }

		$post->update($data);

		return Redirect::route('posts.index');
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		Post::destroy($id);

		return Redirect::route('posts.index');
	}

}

Please note that you're encouraged to modify this generated controller. It simply provides a starting point.

Configuration

You may want to modify your templates - how the generated files are formatted. To allow for this, you need to publish the templates that, behind the scenes, the generators will reference.

php artisan generate:publish-templates

This will copy all templates to your app/templates directory. You can modify these however you wish to fit your desired formatting. If you'd prefer a different directory:

php artisan generate:publish-templates --path=app/foo/bar/templates

When you run the generate:publish-templates command, it will also publish the configuration to app/config/packages/way/generators/config/config.php. This file will look somewhat like:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Where the templates for the generators are stored...
    |--------------------------------------------------------------------------
    |
    */
    'model_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/model.txt',

    'scaffold_model_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/scaffolding/model.txt',

    'controller_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/controller.txt',

    'scaffold_controller_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/scaffolding/controller.txt',

    'migration_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/migration.txt',

    'seed_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/seed.txt',

    'view_template_path' => '/Users/jeffreyway/Desktop/generators-testing/app/templates/view.txt',


    /*
    |--------------------------------------------------------------------------
    | Where the generated files will be saved...
    |--------------------------------------------------------------------------
    |
    */
    'model_target_path'   => app_path('models'),

    'controller_target_path'   => app_path('controllers'),

    'migration_target_path'   => app_path('database/migrations'),

    'seed_target_path'   => app_path('database/seeds'),

    'view_target_path'   => app_path('views')

];

Also, while you're in this file, note that you can also update the default target directory for each generator.

Shortcuts

Because you'll likely type these commands over and over, it makes sense to create aliases.

# Generator Stuff
alias g:m="php artisan generate:model"
alias g:c="php artisan generate:controller"
alias g:v="php artisan generate:view"
alias g:s="php artisan generate:seed"
alias g:mig="php artisan generate:migration"
alias g:r="php artisan generate:resource"

These can be stored in, for example, your ~/.bash_profile or ~/.bashrc files.

laravel-4-generators's People

Contributors

alixg avatar benjaminrh avatar captbrogers avatar chorton2227 avatar danielboendergaard avatar dbwhddn10 avatar freezy-sk avatar fuelingtheweb avatar gmsantos avatar grahamcampbell avatar jeffreyway avatar jontheniceguy avatar mirovit avatar nesk avatar sanspace avatar sherbrow avatar tscheepers avatar white-poto avatar ws avatar xethron 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

Watchers

 avatar  avatar

laravel-4-generators's Issues

Error: Class not found on migration

Hi Jeffrey, when generating a migration e.g: php artisan generate:migration create_releases_table

The migration is created but for some reason the class name is being set wrong (compared to your videos on tutsplus premium + the video in the github description).

It is Pascal Casing the class name. This is then a problem as it’s looking for underscores when running php artisan migrate which it cant find

So for example it is creating:

class CreateReleasesTable extends Migration {
//stuff
}

Then on migrate it throws the error:

<abbr title="Symfony\Component\HttpKernel\Exception\FatalErrorException">FatalErrorException</abbr>: Error: Class 'CreateReleasesTable' not found in /home/{dir}/public_html /vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php line 290

The above issue occurs for me when generating a simple migration and when using the --fields flag.

I also just tried editing the generated file class name to underscores instead but for some reason it still looks for the Pascal case name

p.s I am running PHP Version 5.4.11

Feature Request

When creating a view or a resource (more valuable for resource) create the form fields based off the --fields parameter.

I experimented with this locally and will hopefully be able to spend more time with it in the future, but here is the goal:

php artisan generate:resource task --fields="name:string, message:text, status:string"

This would create all the necessary views and those views would have the markup necessary to update the database with basic records and edit those records.

This may also require some base logic in the controller as well, but it's predictable enough to make it worth while.

The next step would be to have those records printed out with a no records message for the main view. This would also contain edit and delete buttons.

You could even create wrapper templates which the developer could add their own wrapper code; be it bootstrap, another framework, or custom markup.

[Request] Nested Resource Scaffolding

generate:scaffold lists --fields="body:text" --nest="lists.tasks" --tasks-fields="body:text" --rel="hasMany" --nest"lists.tasks.comments" --comments-fields="body:text" --rel="hasMany"

It could use the value of the nest parameter to generate the name of another parameter $nest-fields.

You could then define the relationships in the list, task, and comment models and continue to scaffold nested resources.

I wonder what life will be like with command line generated applications o__0

ps. You do great work, thank you for generator!

README typos

Two of the migration code examples in the readme have up() and up() instead of up() and down().

DB seeding doesn't create timestamps

As it is now the seeding class created is using Fluent to create the data, which apparently doesn't create timestamps.

 DB::table('users')->insert($Users);

I realize it's not all that important to get seeding timestamps as all the records are usually seeded at the same time, but I guess in wouldn't hurt to have an immediate indication of the seeding time.

To tackle this issue, wouldn't it be better to use Eloquent? Something like:

 foreach ($Users as $user) {
        User::create($user);
     }

Errors getting generated scaffold working

I used the following:

php artisan generate:scaffold task --fields="title:string, assignedTo:string, priority:integer"

It seems to generate everything ok. Migration runs fine.

The problem is when I try and create a record it give the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'q' in 'field list' (SQL: insert into `tasks` (`title`, `assignedTo`, `priority`, `q`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?)) (Bindings: array ( 0 => 'Task Test', 1 => 'Shane', 2 => '5', 3 => 'tasks', 4 => DateTime::__set_state(array( 'date' => '2013-05-06 14:57:51', 'timezone_type' => 3, 'timezone' => 'UTC', )), 5 => DateTime::__set_state(array( 'date' => '2013-05-06 14:57:51', 'timezone_type' => 3, 'timezone' => 'UTC', )), ))

Mixed tabs and spaces

When I create a new migration using

php artisan generate:migration create_bookings_table

A class is nicely generated, but it mixes tabs and spaces. I use tabs as a default and therefore I noticed it.

Selection_001

Of course it's really minor, but it still bugs me because Laravel is such a consistently clean-coded framework.

Version conflict on symfony components...

On composer update, this is output
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - don't install laravel/framework 4.0.x-dev|install laravel/framework dev-master
    - Conclusion: don't install laravel/framework dev-master
    - Conclusion: remove laravel/framework v4.0.0-BETA4
    - Conclusion: don't install laravel/framework v4.0.0-BETA4
    - Conclusion: don't install laravel/framework v4.0.0-BETA3
    - Installation request for way/guard-laravel dev-master -> satisfiable by way/guard-laravel dev-master.
    - Conclusion: remove symfony/browser-kit 2.2.x-dev
    - Installation request for laravel/framework 4.0.* -> satisfiable by laravel/framework 4.0.x-dev, laravel/framework v4.0.0-BETA2, laravel/framework v4.0.0-BETA3, laravel/framework v4.0.0-BETA4.
    - Installation request for way/generators dev-master -> satisfiable by way/generators dev-master.
    - laravel/framework v4.0.0-BETA2 requires symfony/browser-kit 2.2.* -> satisfiable by symfony/browser-kit 2.2.x-dev, symfony/symfony 2.2.x-dev, symfony/symfony v2.2.0, symfony/symfony v2.2.0-BETA1, symfony/symfony v2.2.0-BETA2, symfony/symfony v2.2.0-RC1, symfony/symfony v2.2.0-RC2, symfony/symfony v2.2.0-RC3, symfony/symfony v2.2.1, symfony/browser-kit 2.2.x-dev, symfony/browser-kit v2.2.0, symfony/browser-kit v2.2.0-BETA1, symfony/browser-kit v2.2.0-BETA2, symfony/browser-kit v2.2.0-RC1, symfony/browser-kit v2.2.0-RC2, symfony/browser-kit v2.2.0-RC3, symfony/browser-kit v2.2.1.
    - Can only install one of: symfony/symfony 2.3.x-dev, symfony/symfony 2.2.x-dev.
    - Can only install one of: symfony/symfony v2.2.0, symfony/symfony 2.3.x-dev.
    - Can only install one of: symfony/symfony v2.2.0-BETA1, symfony/symfony 2.3.x-dev.
    - Can only install one of: symfony/symfony v2.2.0-BETA2, symfony/symfony 2.3.x-dev.
    - Can only install one of: symfony/symfony v2.2.0-RC1, symfony/symfony 2.3.x-dev.
    - Can only install one of: symfony/symfony v2.2.0-RC2, symfony/symfony 2.3.x-dev.
    - Can only install one of: symfony/symfony v2.2.0-RC3, symfony/symfony 2.3.x-dev.
    - Can only install one of: symfony/symfony v2.2.1, symfony/symfony 2.3.x-dev.
    - don't install symfony/browser-kit 2.2.x-dev|don't install symfony/symfony 2.3.x-dev
    - don't install symfony/browser-kit v2.2.0|don't install symfony/symfony 2.3.x-dev
    - don't install symfony/browser-kit v2.2.0-BETA1|don't install symfony/symfony 2.3.x-dev
    - don't install symfony/browser-kit v2.2.0-BETA2|don't install symfony/symfony 2.3.x-dev
    - don't install symfony/browser-kit v2.2.0-RC1|don't install symfony/symfony 2.3.x-dev
    - don't install symfony/browser-kit v2.2.0-RC2|don't install symfony/symfony 2.3.x-dev
    - don't install symfony/browser-kit v2.2.0-RC3|don't install symfony/symfony 2.3.x-dev
    - don't install symfony/browser-kit v2.2.1|don't install symfony/symfony 2.3.x-dev
    - way/generators dev-master requires symfony/console 2.3.* -> satisfiable by symfony/symfony 2.3.x-dev, symfony/console 2.3.x-dev.
    - Conclusion: don't install symfony/console 2.3.x-dev

After following the instructions up to enter php artisan, returned an error [Segmentation fault: 11]

The Segmentation fault:11 error also came with an html error page which went on to describe the error as so:

Symfony\Component\HttpKernel\Exception\FatalErrorException">FatalErrorException: Parse: parse error in /Applications/MAMP/htdocs/*/vendor/way/generators/src/commands/GenerateMigrationCommand.php line 77

I don't currently have any migrations and I see it's something to do with parsing the MigrationName..

Asset Generation

I noticed in the L3 version of this generator, you gave the ability to generate assets for your project. Is that coming in the L4G, is it a case of duplicating a feature L4 already has, or is it just not a priority?

Either way, it would be nice to see that functionality return

--fields and problem with "

command (from examples)

php artisan generate:resource dog --fields="name:string, age:integer"

generates invalid function to migrations

public function up()
    {
        Schema::create('dogs', function(Blueprint $table) {
            $table->increments('id');
            $table->string('"name');
            $table->integer"('age');
            $table->timestamps();
        });
    }

also seems to be issue with generate:scaffold and generate:migration, probably something related to --fields option ...

Feature Request: Set a field as an ENUM.

If I figure out how to do this, I'll submit a PR.

Does this look like how you would expect to create an ENUM?

artisan generate:scaffold student --fields="forename:string, surname:string, gender:enum['Male','Female']"

Could not create /bootstrap/../app/views/layouts/scaffold.blade.php

I just installed Laravel-4-Generators today and I have just updated Laravel to the latest build. I get this error when I run :

artisan generate:scaffold food --fields="name:string, isGood:boolean, description:text"

I tried different model names and fields with the same result.

Testing controllers but not models

This might not be a question completely related to the package, it will slide into general testing theory as well. But I was playing around with it and found my favorite command, which of course was resource:generate.

What struck me was that only a test file for the controller was generated but not the model itself. And it's this I would like to know your thoughts behind, do you find it sufficient writing tests for the controller only and not the model? Do you consider that the model will be thoroughly tested if you write a good test for the controller?

migration rollback

i've tried generator to generate a migration and it has worked pretty awesome but when i've tried to rollback i had an error which tells that i could not find my migration class.

I'm using laravel 4

Wrong format when using generate:seed (check before closing)

Since you closed the other issue without testing I am opening it again. If I am wrong please correct me but there is still an issue.

While both the below in theory may mean the same thing they are NOT working the SAME.

Such as:

The below will only insert the VERY LAST entry 'Classics' into the DB table, skipping the first 8:

$cartypes = array(
            'type' => 'Sedans',
            'type' => 'Coupes',
            'type' => 'Convertibles',
            'type' => 'Luxury Cars',
            'type' => 'Pickup Trucks',
            'type' => 'SUVs / Crossovers',
            'type' => 'Minivans / Vans',
            'type' => 'Green / Hybrids',
            'type' => 'Classics'

        );

This one will not insert anything. Which I figured it would not. Just produces an error:

$cartypes = array(
            'Sedans',
            'Coupes',
            'Convertibles',
            'Luxury Cars',
            'Pickup Trucks',
            'SUVs / Crossovers',
            'Minivans / Vans',
            'Green / Hybrids',
            'Classics'

        );

Produces the following error:

  [Exception]
  SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into `cartypes` (`0`, `1`,
  `2`, `3`, `4`, `5`, `6`, `7`, `8`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)) (Bindings: array (
    0 => 'Sedans',
    1 => 'Coupes',
    2 => 'Convertibles',
    3 => 'Luxury Cars',
    4 => 'Pickup Trucks',
    5 => 'SUVs / Crossovers',
    6 => 'Minivans / Vans',
    7 => 'Green / Hybrids',
    8 => 'Classics',
  ))



db:seed [--class[="..."]] [--database[="..."]]

Works properly.

$cartypes = [
            ['type' => 'Sedans'],
            ['type' => 'Coupes'],
            ['type' => 'Convertibles'],
            ['type' => 'Luxury Cars'],
            ['type' => 'Pickup Trucks'],
            ['type' => 'SUVs / Crossovers'],
            ['type' => 'Minivans / Vans'],
            ['type' => 'Green / Hybrids'],
            ['type' => 'Classics']  
        ];

The below also works properly, but reading the docs does not specify this structure:

$cartypes = array(
            array(
                'type' => 'Sedans'                                                                              
            ),
            array(
                'type' => 'Coupes'
            ),
            array(
                'type' => 'Convertibles'
            ),
            array(
                'type' => 'Luxury Cars'
            ),
            array(
                'type' => 'Pickup Trucks'
            ),
            array(
                'type' => 'SUVs / Crossovers'
            ),
            array(
                'type' => 'Minivans / Vans'
            ),
            array(
                'type' => 'Green / Hybrids'
            ),
            array(
                'type' => 'Classics'
            ));

So while it is not a bug as I initially thought. It might be a benefit to update the docs to use the proper structure.

Regards,
Ray

[SOLVED] Error with generate:resource

The Laravel 4 update this morning fixed it! Will probabily fix others errors as well.

c:\xampp\htdocs\cms>php artisan generate:resource page --fields="parent:integer:default[0], name:str
ing, slug:string, title:string,
{"error":{"type":"ErrorException","message":"Undefined offset: 1","file":"C:\xampp\htdocs\cms\ve
ndor\way\generators\src\Way\Generators\Cache.php","line":58}}
c:\xampp\htdocs\cms>
c:\xampp\htdocs\cms>keywords:string, body:text, order:integer:default[0], special:integer:nullable,
template:string, pagetype:string
The filename, directory name, or volume label syntax is incorrect.

c:\xampp\htdocs\cms>
c:\xampp\htdocs\cms>[64]:nullable, desc:string, assocdate:date:nullable, vars:text"

generate:form doesn't work with DB prefix?

I get the form but without any column information. Just the open/close tags of the form. I forced the model to use the table name with the prefix I use, again nothing changed.

Readme example confusion

Your Forms example is talking about dogs, but the code is about a tweet. Just thought I'd let you know.

Wrong format when using generate:seed

Hello,

When using php artisan generate:seed cartypes for instance the array generated is like so:

$cartypes = array(

        );

The documentation states it should generate the file like so:

$cartypes = [

        ];

This works properly when changed. The output at current is generating the wrong template for the seed file.

Regards,
Ray

Generate:Resource Rollback?

Is there a rollback for generated resources? I'm just trying to learn Laravel, and find that I'm having to hunt down and delete all the files generated after I realize I didn't need them at all. In the past, I'd just nuke the directory to something like this. But with the use of composer, it's a little more effort to get things going it seems.

Just a thought. Thanks for the great work!

Feature Request - Support view templates

It would be quite helpful if the generated view files could use some sort of basic template. Yes, I can surely copy/paste my templates over the generated files but since it is doing this step anyway (I typically create resources) it would be nice if the created view files were a bit "smarter".

Perhaps storing the templates in the stub directory and if a template does exist, use it? If you are keen on the idea but don't have time to add features, I can do it for you.

generate:migration gives error

➜ laravel4 git:(master) ✗ php artisan generate:migration create_followers_table
PHP Fatal error: Call to undefined method Meido\Str\Str::camel() in /home/rajivseelam/Sites/laravel4/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 135

In /vendor/way/generators/src/commands/GenerateMigrationCommand.php, In method applyDataToStub, the following is giving problem:

$stub = str_replace('{{name}}', \Str::camel($this->argument('fileName')), $stub);

The following change worked:
$stub = str_replace('{{name}}', str_replace('_', '',\Str::classify($this->argument('fileName'))), $stub);

There is a classify method in str which converts into camel case but with underscores. So, again used str_replace to remove underscores. I am not sure if this is how I should submit the patch to git (?).

correct syntax for decimal with precision and scale

Hello Jeffrey.
I am having trouble using the syntax ':decimal[10,5]' or even ':decimal(10,5)' and am getting errors. If I don't enter the precision and scale parameters there is no problem. Any idea if this is a bug?
Thanks.

Error using generate:form with enum type

Using the generate:form command for a model that contains an enum throws a Doctrine exception

[Doctrine\DBAL\DBALException]                                                                    
  Unknown database type enum requested, Doctrine\DBAL\Platforms\MySqlPlatform may not support it. 

Feature/Question

Is there a reason why creating standard controllers has been omitted? (not resourceful)
In the L3 version you could do:
php artisan generate:controller Admin index show doSomething

Even the ability to add on additional methods to the controller would be useful.
Or should I not be placing other methods like this in the same controller, as I am not always certain where I should place my methods that are not linked to a rest request.

Hope that makes sense and I am not just waffling.

Thanks

[Request] Add pre-built forms to create and edit views on generate:resource

I'd love it if I generated a resource, it would know to pre-populate my relevant views with the probable code.

Say I was to run php artisan generate:resource dog --fields="name:string, bio:text" it would know to add similar to what I have below to dogs/edit.blade.php and dogs/create.blade.php views:

{{ Form::model($dog, ['route' => ['dogs.update', $dog->id], 'method' => 'PUT']) }}

    <p>
        {{ Form::label('name'); }}
        {{ Form::text('name'); }}
    </p>

    <p>
        {{ Form::label('bio'); }}
        {{ Form::textarea('bio'); }}
    </p>

    <p>
        {{ Form::submit(); }}
    </p>

{{ Form::close() }

At the same time, I could see this feature becoming maybe too opinionated in that we might as well generate the default list view for the index.blade.php page. Perhaps this feature would be worth a fork?

The table name in the seeder is capitalized, should be lowercase

After running php artisan generate:resource thing --fields="name:string, description:text", the ThingsTableSeeder.php file produced is:

<?php

class ThingsTableSeeder extends Seeder {

  public function run()
  {
    $Things = [

    ];

    DB::table('Things')->insert($Things);
  }

}

The table name is capitalized, but should be lowercase. Everywhere else seems to be correct though, for instance, the migration produced uses lower case 'things' as the table name.

Using the latest version of the L4 generators (I just did a composer update).

Btw, great work on this generator. It's wonderful!

Resources/scaffolds generated with underscore in name should be capitalized

Currently, when a resource or scaffold is generated with generate:resource/scaffold some_thing the result is Some_thingsController, with filename Some_thingsController.php, and the same thing for the models, etc.

I think the vast majority of times in this case, the user would prefer to have the results be SomeThing, with a database name of some_thing. So, for example, some_thing would result in:

  • SomeThing model at models/SomeThing.php
  • SomeThingsController at controllers/SomeThingsController.php
  • etc.

Real examples of this include a github_users table with the GithubUser model rather than the Github_user model, etc.

Make blade templates optional

Please add a setting to switch between normal views and blade views.
Now I have to change the view file names after the generating.

very minor formatting issue in migration

line 197 src/commands/GenerateMigrationCommand.php

return implode("\n\t\t\t", $template);

There is a extra tab that only seems to affect the second field, pushing it over too far.

I removed one of them and it all lines up.

View [layouts.scaffold] not found.

I'm new to Laravel 4, and am just experimenting with the generators at the moment. After running the scaffold generator I got this error.

View [layouts.scaffold] not found.

In case anyone else has this issue, here is what I did to fix it. Create this file:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <div class="container">
            @yield('main')
        </div>
    </body>
</html>

Save it as app/views/layouts/scaffold.blade.php

Str is not defined

PHP Fatal error:  Class 'Str' not found in /Users/USERNAME/project/vendor/way/generators/src/commands/GenerateMigrationCommand.php on line 118

I get this error when I try to generate a migration.

Please tag a 0.1.0 release according to composer and semver.org recommendations

Hi Jeff,

Thanks for your work on this. We are moving toward a working release of our site and need to peg composer to a specific version of this package. I understand your project is still under development, but it does carry useful features that we have come to depend on. So following recommendations made by the following sites, please create a 0.1.0 tag in this project to reflect its current level of stability.

https://igor.io/2013/01/07/composer-versioning.html

http://semver.org/

Thanks again!

Jon

Multiple projects

There are some issues with using generator Sublime text 2 plugin with multiple projects.
If i have opened 2 projects and opened file in second project - using generator it will generate "resource" as example to first project.

Calling show method from resource

I am trying to call the show method but it doesn't seem to work. If I call as

/photos/show

All works (but no id defined)

/photos/3/show
/photos/show/3

Don't work, I am expecting it to work like the edit method

/photos/3/show

The class method expects $id so I would think above syntax would be correct (just like edit method)

Is the method created by generator incorrect? What is correct syntax for accessing show?

environments support

Would love to see environments support for generate:form so that

./artisan generate:form Dog --env=local

will use the local db environment
thanks

Syntax error unexpected [

Great script. not sure if it’s my setup or a bug but when I installed via composer all the [] arrays threw an error.

PHP Parse error: syntax error, unexpected '['

Changing [] to array() in all cases fixed the issue for me.

[Request] generate:controller

I am moving to Laravel 4, and I missed this one. I don't know why it's removed, is it because of best practices or to move to RESTful controllers... But this one is needed because we need simple controllers sometimes, especially when regrouping routes.

Issue/Question local environment

There's a way to put 'Way\Generators\GeneratorsServiceProvider' just in a local providers? If I use in dev env, the production environment wouldn't have the generator... I don't want it, either.

Thanks! (y)

Nothing happens.

I'm not sure what I'm doing wrong here.

php artisan generate commands work from the command line, but trying to do anything using the plugin, even Laravel Artisan Command, doesn't do anything. I get no status_message, so I'm not sure what's wrong; it just does nothing.

Any ideas what I'm missing?

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.