Laravel File Generators with config and publishable stubs

Overview

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 to generate.

This package is being used in the Admin Starter Project that focusses on test driven development and has the foundation ready for you.

Laravel 5.1 : v2.1.3
Laravel 5.2 - 5.3 : v3.0.3
Laravel 5.4 : v4.1.9
Laravel 5.5 - 5.8 : v5.0.0+
Laravel 6.0 : v5.1.0+
Laravel 7.0 : v6.0
Laravel 8.0 : v7.0+

Commands

php artisan generate:publish-stubs
php artisan generate:model
php artisan generate:view
php artisan generate:controller
php artisan generate:migration
php artisan generate:migration:pivot
php artisan generate:seed
php artisan generate:resource
php artisan generate:repository
php artisan generate:contract
php artisan generate:notification
php artisan generate:event
php artisan generate:listener
php artisan generate:event-listener
php artisan generate:trait
php artisan generate:job
php artisan generate:console
php artisan generate:middleware
php artisan generate:factory
php artisan generate:test
php artisan generate:file
php artisan generate:exception

Option for all the commands

--force This will override the existing file, if it exists.

Option for all the commands, except views and migration:pivot

--plain This will use the .plain stub of the command (generate an empty controller)

Customization

This is for all except the migration and migration:pivot commands

php artisan generate:file foo.bar --type=controller
php artisan generate:view foo.bar --stub=view_show --name=baz_show
php artisan generate:file foo.bar --type=controller --stub=controller_custom --name=BazzzController --plain --force

You can specify a custom name of the file to be generated. You can add the --plain or --force options. You can override the default stub to be used. You can create your own stubs with the available placeholders. You can create new settings' types, for example:

  • 'exception' => ['namespace' => '\Exceptions', 'path' => './app/Exceptions/', 'postfix' => 'Exception'],

Available placeholders

Views Custom Stubs

php artisan generate:view posts
php artisan generate:view admin.posts --stub=custom
php artisan generate:view admin.posts --stub=another_file

Installation

Update your project's composer.json file.

composer require bpocallaghan/generators --dev

Add the Service Provider (Laravel 5.5+ has automatic discovery of packages) You'll only want to use these generators for local development, add the provider in app/Providers/AppServiceProvider.php:

public function register()
{
    if ($this->app->environment() == 'local') {
        $this->app->register(\Bpocallaghan\Generators\GeneratorsServiceProvider::class);
    }
}

Run php artisan command to see the new commands in the generate:* section

Usage

Models

php artisan generate:model bar
php artisan generate:model foo.bar --plain
php artisan generate:model bar --force
php artisan generate:model bar --migration --schema="title:string, body:text"

Views

php artisan generate:view foo
php artisan generate:view foo.bar
php artisan generate:view foo.bar --stub=view_show
php artisan generate:view foo.bar --name=foo_bar

Controllers

php artisan generate:controller foo
php artisan generate:controller foo.bar
php artisan generate:controller fooBar
php artisan generate:controller bar --plain
php artisan generate:controller BarController --plain
  • The Controller postfix will be added if needed.

Migrations

This is very similar as Jeffrey Way's

php artisan generate:migration create_users_table
php artisan generate:migration create_users_table --plain
php artisan generate:migration create_users_table --force
php artisan generate:migration create_posts_table --schema="title:string, body:text, slug:string:unique, published_at:date"

Pivot Tables

This is very similar as Jeffrey Way's

php artisan generate:migration:pivot tags posts

Database Seeders

php artisan generate:seed bar
php artisan generate:seed BarTableSeeder
  • The TableSeeder suffix will be added if needed.

Resource

php artisan generate:resource bar
php artisan generate:resource foo.bar
php artisan generate:resource foo.bar_baz
php artisan generate:resource bar --schema="title:string, body:text, slug:string:unique, published_at:date"
php artisan generate:resource articles --controller=admin
  • This will generate a Bar model, BarsController, resources views (in config), create_bars_table migration, BarTableSeeder
  • In the config there is a resource_views array, you can specify the views that you want to generate there, just make sure the stub exist.
  • This will also ask you to generate the 'repository - contract pattern' files.
  • The --controller=admin allows you to use the controller_admin stub when generating the controller.

Repository

php artisan generate:repository Posts

This will generate a Posts Repository file to be used in your controller.

Contract

php artisan generate:contract Cache

This will generate a Cache Contract file to be used with your repositories.

Notifications

php artisan generate:notification UserRegistered

This will generate a UserRegistered notification. Laravel provides support for sending notifications across a variety of delivery channels, including mail, SMS (via Nexmo), and Slack. Notifications may also be stored in a database so they may be displayed in your web interface.

Events and Listeners

php artisan generate:event InvoiceWasPaid
php artisan generate:listener NotifyUserAboutPayment --event=InvoiceWasPaid
php artisan generate:event-listener

This will generate the event and listener. Laravel's events provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application

php artisan generate:event-listener Will generate all the missing events and listeners defined in your EventServiceProvider.

Trait

php artisan generate:trait Http\Controllers\Traits\Bar

This will generate a FooBar Trait file. The command will use the name as your namespace. generate:trait Foo will create a file in app/Foo.php, generate:trait Foo\Bar will create a file in app/Foo/Bar.php.

Job

php artisan generate:job SendReminderEmail

This will generate a SendReminderEmail Job file.

Console (Artisan Command)

php artisan generate:console SendEmails
php artisan generate:console SendEmails --command=send:emails

This will generate a SendEmails Artisan Command file. The --command option is optional.

Middleware

php artisan generate:middleware AuthenticateAdmin

This will generate an AuthenticateAdmin Middleware file.

Factory

php artisan generate:factory Post
php artisan generate:factory PostFactory

This will generate a PostFactory model file.

Test

php artisan generate:test UserCanLogin
php artisan generate:test Post --unit
php artisan generate:test Auth\LoginTest

This will generate Feature\UserCanLogin and Unit\PostTest and Unit\Auth\LoginTest files.

Configuration

php artisan generate:publish-stubs

This will copy the config file to /config/generators.php. Here you can change the defaults for the settings of each type, like model, view, controller, seed. You can also change the namespace, path where to create the file, the pre/post fix, and more. You can also add new stubs.

This will also copy all the stubs to /resources/stubs/. Here you can make changes to the current stubs, add your own boilerplate / comments to the files. You can also add your own stubs here and specify it in the config to be used. Migration Stub Note: The migration.stub is only the outer part and the schema_create.stub or schema_change.stub is where you modify the schema itself. The schema_create.stub has boilerplate added to it.

File

This is the base command for the view, model, controller, seed commands. The migration and migration:pivot uses Jeffrey's classes. In the config there is a settings array, this is the 'types' and their settings. You can add more, for example, if you use repositories, you can add it here.

php artisan generate:file foo.bar --type=view
php artisan generate:file foo.bar --type=controller
php artisan generate:file foo.bar --type=model
php artisan generate:file foo.bar --type=model --stub=model_custom

Shortcuts

art=php artisan
model=php artisan generate:model
view=php artisan generate:view
view:index=php artisan generate:view:index
view:create_edit=php artisan generate:view:create_edit
view:show=php artisan generate:view:show
controller=php artisan generate:controller
migration=php artisan generate:migration
migration:pivot=php artisan generate:migration:pivot
seed=php artisan generate:seed
resource=php artisan generate:resource

Customizing file was created message to add support for ide opening the files

Make links for opening output.Add output_path_handler as a function to your config/generators.php.Example:

'output_path_handler' => static function($path){
    return 'file:///' . base_path() . $path;
},

This will output a file schema uri which JetBrain Products (Intellij,Php Storm,Web Storm,...) then can open directly from your terminal.

Thank you

My Other Packages

  • Alert A helper package to flash a bootstrap alert to the browser via a Facade or a helper function.
  • Notify Laravel Flash Notifications with icons and animations and with a timeout
  • Impersonate User This allows you to authenticate as any of your customers.
  • Sluggable Provides a HasSlug trait that will generate a unique slug when saving your Laravel Eloquent model.
Comments
  • Trait 'Illuminate\Console\DetectsApplicationNamespace' not found in Laravel 5.3

    Trait 'Illuminate\Console\DetectsApplicationNamespace' not found in Laravel 5.3

    Hello,

    I just noted this issue, you might be aware but still just mentioning here.

    Class ListenerCommand, FileCommand which use the 'DetectsApplicationNamespace' trait which is present only after 5.4. So please either add minimum Laravel version in a composer.json & readme.md or use AppNamespaceDetectorTrait for an older version.

    Thanks.

    opened by nikkanetiya 15
  • Inject methods into models during generate:migration:pivot foo bar

    Inject methods into models during generate:migration:pivot foo bar

    Not an issue, but would be helpful.

    During this process would it make sense to automatically establish the many-to-many relationship between foo and bar put

    In the Bar model:

    public function foos() { return $this->(Belongs to many stuff here with the 4 parameters) }

    In the Foo model

    public function bars(){ return $this->belongsToMany( inverse of above not needing the 4 parameters??) }

    Thoughts?

    enhancement 
    opened by maddeezy 15
  • generate pivot table missing Name

    generate pivot table missing Name

    Ex:

    When I run the generate:migration:pivot foos bars

    The migration created is created as:

    class extends Migration {

    (missing the name)

    I believe it should be

    class CreateFooBarPivotTable extends Migration {

    I don't see that this function is being called anywhere during the pivot migration

    protected function parseName($name) { $tables = array_map('str_singular', $this->getSortedTableNames()); $name = implode('', array_map('ucwords', $tables));

        return "Create{$name}PivotTable";
    }
    

    From the: public function fire() { $name = $this->qualifyClass($this->getNameInput()); ......

    It looks like it is calling only /** * Empty 'name' argument * * @return string */ protected function getNameInput() { // }

    Which of course will return an empty name

    In the meantime, I'll just type that in

    Thanks

    bug 
    opened by maddeezy 8
  • Config and publishing stubs

    Config and publishing stubs

    I can't publish the config file using php artisan vendor:publish, nor does it publish the stubs. Is there specific way of doing this, or will you implement the publishes() method in the service provider to automatically export them?

    Thanks

    opened by markcameron 7
  • Migration is auto populated with personal preferences.

    Migration is auto populated with personal preferences.

    Using this command :

    php artisan generate:model bar --migration --plain

    It created a migration with this up method :

      public function up()
        {
            Schema::create('bars', function (Blueprint $table) {
                $table->bigIncrements('id')->unique()->index();
                
                $table->timestamps();
                $table->softDeletes();
                $table->integer('created_by')->unsigned();
                $table->integer('updated_by')->unsigned()->nullable();
                $table->integer('deleted_by')->unsigned()->nullable();
            });
        }
    

    I don't want these auto generated fields from out of nowhere to come they were not in the stub file as well.

    opened by Stevemoretz 5
  • Enhancement for repositories/contracts

    Enhancement for repositories/contracts

    Would it be possible to also add stubs for repositories and contracts?

    Our project is growing and it would be nice to stub out this when we use generate:resource foo and maybe add flags to include a repository and contract?

    What do you think?

    We also came across the quasar framework

    Totally Vue..pretty nice...thought I would share.

    http://quasar-framework.org

    enhancement question 
    opened by maddeezy 5
  • generate:migration:pivot has inverted classes

    generate:migration:pivot has inverted classes

    When we use this command and inject the many to many relationship in the model, the classes are inverted.

    Example

    generate:migration:pivot bar foo

    would currently add in the Foo Class Model

    public function bars() { return $this->belongsToMany(Foo::class); }

    I believe it should be

    public function bars() { return $this->belongsToMany(Bar::class); }

    opened by maddeezy 3
  • Composer Update doesn't recognize existing stubs

    Composer Update doesn't recognize existing stubs

    Hey Ben-Piet!

    It's been awhile, I saw the update so I ran it...

    However, if stubs are already published, they need to be published again with --force in order for them to be used...I just cleaned in git all my existing stubs, then it worked...

    opened by maddeezy 3
  • PHP 8 Compat

    PHP 8 Compat

    Hi,

    It looks like this package is locked to PHP 7:

    - bpocallaghan/generators is locked to version 7.0.1 and an update of this package was not requested.
    - bpocallaghan/generators 7.0.1 requires php ^7.3 -> your php version (8.0.3) does not satisfy that requirement.
    
    opened by nabeelio 2
  • Validator idea

    Validator idea

    Validator idea... Also, I never run the migration at the time of generate:resource since there are only a few things that are common, the rest gets built, then the migration is performed. Once performed, it would be great to do some like:

    generate:validator foo_bar

    And then using Doctrine/dbal we could get the schema and inject the proper validator in the store and update of the FooBarController (at least all of the required fields.)

    enhancement 
    opened by bpocallaghan 2
  • Consistency in {{resource_name}} in Controllers

    Consistency in {{resource_name}} in Controllers

    Love the package...using it daily.

    However, in using:

    generate:resource example_resource

    In the controller section, it is not consistent with the others like view, model, etc...

    It changes the {{resource_name}} to {{resourceName}}

    I commented out the code here:

    private function callController() { $name = $this->getResourceControllerName(); if ($this->confirm("Create a controller ($name) for the $this->resource resource? [yes|no]")) { $arg = $this->getArgumentResource(); $name = substr_replace($arg, str_plural($this->resource), strrpos($arg, $this->resource), strlen($this->resource)); // foo.bar_baz == foo.barBaz //$pieces = explode('_', $name); //$name = ""; //foreach ($pieces as $k => $str) { // $name .= ucfirst($str); //} $this->callCommandFile('controller', $name); } }

    Now works as expected, unless I am missing why we would go fooBar instead of foo_bar when we use: php artisan generate:resource foo_bar

    Of course the model being FooBar is understandable...but when we call {{resource_name}} in the other sections...it gives foo_bar as expected.

    Thanks for the hard work!

    Erik

    opened by maddeezy 2
  • Some feature request and speaking of generate::request

    Some feature request and speaking of generate::request

    Hi, I was thinking about what you've done here.You know that message that says

    .somepath/some/test.bladee.php Was generated At the end.I guess it could be great if in config/generator.php

    A function could be defined to handle that message.

    You may think what kind of stupid feature is that :D

    But the purpose is that you can do a few stuff here to open the files that were generated in the ide.

    Since I think it isn't such a great idea to handle all these ide opening stuff yourself because I see you're working alone on this, I guess that would be a lot better so you can do a few ones and let the rest of it to the other ide users.

    There are two possible ways to open a file in ide from php.

    Either output a link like idea://blahblah... Which is a link that when opens gets you there. Or some ideas again like intellij suppert a command for opening files in terminal so a exec() in php could do that or again intellij can open files in this link too : file:///path.blade.php

    So you get the point,that could let the users do any of these ways in their ides which I think is a great idea.


    The other thing you said generate::request

    I don't know what that is but in a few days I'm making something which basically makes adding somethings like routes in web.php automated from php well essentially I'm doing it for some other reason, but if that's something like what you need, I'll provide the code to what I've done when it's done and also can help you adapt it for your own use case.It's just a little playing with regex. But I guess you won't need my help. Anyways it never hurts to hear somebody offers some help.

    enhancement help wanted 
    opened by Stevemoretz 2
Releases(8.0.2)
Owner
Ben-Piet O'Callaghan
Full Stack Developer at GDC Media and Laravel Developer at Bookamat
Ben-Piet O'Callaghan
A simple way to generate files from stubs.

STUBBY A simple way to generate files from stubs. Usage For example we have a stub file that looks like this: <?php namespace {{ namespace }}; use A

Prince John Santillan 4 May 12, 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
Rapidly speed up your Laravel workflow with generators

Fast Workflow in Laravel With Custom Generators This Laravel package provides a variety of generators to speed up your development process. These gene

Jeffrey Way 22 Oct 28, 2022
Laracademy Generators - is a tool set that helps speed up the development process of a Laravel application.

Laracademy Generators Laracademy Generators - is a tool set that helps speed up the development process of a Laravel application. Author(s): Laracadem

Laracademy 320 Dec 24, 2022
Renamify is a package for Laravel used to rename a file before uploaded to prevent replacing exists file which has the same name to this new uploaded file.

Renamify Laravel package for renaming file before uploaded on server. Renamify is a package for Laravel used to rename a file before uploaded to preve

MB'DUSENGE Callixte 2 Oct 11, 2022
A Laravel package that allows you to validate your config values and environment.

Table of Contents Overview Installation Requirements Install the Package Publishing the Default Rulesets Usage Creating a Validation Ruleset Using the

Ash Allen 152 Dec 15, 2022
Sebuah aplikasi file hosting sederhana yang berguna untuk menyimpan berbagai file

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Willy Ferry 2 Nov 25, 2021
Laravel Livewire (TALL-stack) form generator with realtime validation, file uploads, array fields, blade form input components and more.

TALL-stack form generator Laravel Livewire, Tailwind forms with auto-generated views. Support Contributions Features This is not an admin panel genera

TinaH 622 Jan 2, 2023
Auto-generated Interface and Repository file via Repository pattern in Laravel

Auto-generated Repository Pattern in Laravel A repository is a separation between a domain and a persistent layer. The repository provides a collectio

Ngo Dinh Cuong 11 Aug 15, 2022
Laravel Larex lets you translate your whole Laravel application from a single CSV file.

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

Luca Patera 68 Dec 12, 2022
A simple pure PHP RADIUS client supporting Standard and Vendor-Specific Attributes in single file

BlockBox-Radius A simple pure PHP RADIUS client supporting Standard and Vendor-Specific Attributes in single file Author: Daren Yeh [email protected]

null 2 Oct 2, 2022
Laravel File System Watcher

Lara Inotify is a wrapper for inotify for Laravel to make it easier to watch filesystem and avoid memory leaks.

Octopy ID 13 Nov 5, 2022
Orbit is a flat-file driver for Laravel Eloquent

Orbit is a flat-file driver for Laravel Eloquent. It allows you to replace your generic database with real files that you can manipulate using the methods you're familiar with.

Ryan Chandler 664 Dec 30, 2022
Stapler-based file upload package for the Laravel framework.

laravel-stapler Laravel-Stapler is a Stapler-based file upload package for the Laravel framework. It provides a full set of Laravel commands, a migrat

Code Sleeve 565 Dec 9, 2022
File manager for Laravel

Laravel File Manager DEMO: Laravel File Manager Vue.js Frontend: alexusmai/vue-laravel-file-manager Documentation Laravel File Manager Docs Installati

Aleksandr Manekin 937 Jan 1, 2023
Store your Laravel application settings in an on-disk JSON file

Store your Laravel application settings in an on-disk JSON file. This package provides a simple SettingsRepository class that can be used to store you

Ryan Chandler 24 Nov 16, 2022
Stapler-based file upload package for the Laravel framework.

laravel-stapler Laravel-Stapler is a Stapler-based file upload package for the Laravel framework. It provides a full set of Laravel commands, a migrat

Code Sleeve 565 Dec 9, 2022
Laravel Model File Uploader package

Laravel Model File Uploader package Easy way to upload laravel model related file from the requset. Install (Via Composer) composer require plusemon/u

Emon Khan 5 Dec 15, 2022
Trait for multilingual resource file support

⚡ Usage This library supports MultilingualResourceTrait which can be used in PluginBase. Multilingual support of resource files is possible using this

PocketMine-MP projects of PresentKim 1 Jun 7, 2022