Code Monkey home page Code Monkey logo

generators's Introduction

Backpack Generators

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Style CI Total Downloads

Quickly generate Backpack templated Models, Requests, Views and Config files for projects using Backpack for Laravel as their admin panel.

Security updates and breaking changes

Please subscribe to the Backpack Newsletter so you can find out about any security updates, breaking changes or major features. We send an email every 1-2 months.

Install

Via Composer

composer require --dev backpack/generators

// OPTIONAL: if you would like to change Backpack generated files you can publish the stubs with:
php artisan vendor:publish --tag=backpack-generators-stubs

Usage

Open the console and enter one of the commands:

  • Generate Backpack\CRUD interfaces for all Eloquent models that don't already have one:
php artisan backpack:build
  • Generate all files for one new Backpack\CRUD interface:
php artisan backpack:crud {Entity_name}

# Use singular, either PascalCase, snake_case or kebab-case.
# This will create a Model if there isn't one, or add
# our CrudTrait to the model if it already exists.
  • Generate all files for a custom admin panel page:
php artisan backpack:page {PageName}

# You can use either PascalCase, snake_case or kebab-case.
# This will generate you a Controller, a view and a route.
  • Generate a new Backpack\CRUD file:
php artisan backpack:crud-controller {Entity_name}
php artisan backpack:crud-model {Entity_name}
php artisan backpack:crud-request {Entity_name}
  • Generate a model (available options: --softdelete)
php artisan backpack:model {Entity_name}
  • Generate a request
php artisan backpack:request {Entity_name}
  • Generate a view (available options: --plain)
php artisan backpack:view {Entity_name}
  • Generate a config file
php artisan backpack:config {Entity_name}
  • Generate a button
php artisan backpack:button {button_name}
  • Generate a field
php artisan backpack:field {field_name}

// or generate a field starting from another field
php artisan backpack:field {field_name} --from={original_field_name}
  • Generate a column
php artisan backpack:column {column_name}

// or generate a column starting from another column
php artisan backpack:column {column_name} --from={original_column_name}
  • Generate a filter
php artisan backpack:filter {filter_name}

// or generate a filter starting from another filter
php artisan backpack:filter {filter_name} --from={original_filter_name}
  • Generate a widget
php artisan backpack:widget {widget_name}

// or generate a widget starting from another widget
php artisan backpack:widget {widget_name} --from={original_widget_name}
  • Generate a custom operation
php artisan backpack:crud-operation {OperationName}
  • Generate a custom form operation
php artisan backpack:crud-form-operation {OperationName}

Change log

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Credits

License

Backpack is free for non-commercial use and 69 EUR/project for commercial use. Please see License File and backpackforlaravel.com for more information.

Hire us

We've spend more than 50.000 hours creating, polishing and maintaining administration panels on Laravel. We've developed e-Commerce, e-Learning, ERPs, social networks, payment gateways and much more. We've worked on admin panels so much, that we've created one of the most popular software in its niche - just from making public what was repetitive in our projects.

If you are looking for a developer/team to help you build an admin panel on Laravel, look no further. You'll have a difficult time finding someone with more experience & enthusiasm for this. This is what we do. Contact us. Let's see if we can work together.

generators's People

Contributors

abbyjanke avatar dependabot-preview[bot] avatar dependabot[bot] avatar diogogomeswww avatar egyjs avatar errogaht avatar flartet avatar ghitu avatar imokhles avatar juanem1 avatar juniorgarcia avatar karandatwani92 avatar maarten00 avatar mattsches avatar maurohmartinez avatar o15a3d4l11s2 avatar oliverziegler avatar owenmelbz avatar pavoltanuska avatar piterden avatar pleone avatar promatik avatar pxpm avatar shadowbane avatar siberfxweb avatar stylecibot avatar tabacitu avatar votintsev 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

generators's Issues

Not getting the Calendar icon in the widget like in the Doc

Hello,

Laravel 6
Backpack 4

On this page:
https://backpackforlaravel.com/docs/4.0/crud-fields#datetime

It shows a little calender icon in the field but it is not showing up when using the doc code as:

1

But this code from the doc:

        $this->crud->addField([
            'name' => 'published_at',
            'label' => 'Date',
            'type' => 'date_picker',
            'date_picker_options' => [
                'todayBtn' => 'linked',
                'format' => 'dd-mm-yyyy',
                'language' => 'en'
            ],
        ]);

Does not output the icon at all. Please see the pick after I add the code to my Controller

1

Is it possible to update the correct code in the doc please?

Thank you.

[Improvement] Change CRUD command & route from singular to plural

Right now we ask people to run

php artisan backpack:crud tag # use singular, not plural

Which is a little counter-intuitive. Since the db table is plural, I think it'll be easier for people to run the plural name instead. We chose to use the singular because, in the past, the Laravel best practice was to use singular for Resource Routes, and for Controller name. Now the best practice is to have plural for resource route (Route::resource('tags', 'TagController');) but still singular for Controller name. That's why, I think, in addition to changing the command from singular to plural, we should also change the route. So that it's:

-admin/tag
-admin/tag/create
-admin/tag/update
+admin/tags
+admin/tags/create
+admin/tags/update

But this means we need to be super-sure about both the single and plural name, basically asking both from the user. So maybe instead we should do something like this:

php artisan backpack:crud                           # no mandatory parameters

# What's the table in the database?
> tags
     # [ERROR] Did not find table "tags" in the database.
# Confirm or edit your entity name, in plural, in English? (ex: tags, products, users)
> tags
# Confirm or edit your entity name, in singular, in English? (ex: tag, product, user)
> tag
# Found Model "App\Tag" - do you want to use it? (y/n)
#    (N) > Where do you want to generate your new Model?
         > App\Models\Tag
#
# ---------------
# Generated app/Models/Tag.php
# Generated app/Http/Requests/Tag.php
# Generated app/Http/Controllers/Admin/TagCrudController.php
# Added Route::crud('tag', 'TagCrudController'); to routes/backpack/custom.php
# Added sidebar item to resources/views/vendor/backpack/base/inc/sidebar_contents.blade.php
# ---------------
#       Done 
# ---------------

Once you specify the table name (tags) we can offer sensible defaults for the rest of the prompts:

  • we already have the name of the entity in plural - tags;
  • we can get the singular by stripping the "s" - tag;
  • we can check the app folder for any class that extends Model that is either called Tag.php, or has $table = 'tags'; inside it; to see if the dev already has a Model they might want to use;
  • we know a good name place for the generated Model would be App\Models\Tag.php

This way, you don't have to remember if it's singular or plural, the command-line prompt tells you exactly what it needs. You just need to remember php artisan backpack:crud - which is super-easy to remember. Possible alias: php artisan make:crud. For backwards-compatibility, we should probably keep the "singular" as an OPTIONAL parameter. Or we could leave php artisan backpack:crud as-is, and create this new command php artisan make:crud which is more powerful. But I see no point in having both, tbh.

To sum up, what I propose we do here:

  • make parameter in php artisan backpack:crud optional;
  • prompts to ask for the table name; then ask to confirm both singular and plural form of the entity; and if there's already a Model, ask if they want to use the existing model;
  • change CRUD route to use plural form, just like table name: Route::crud('tags', 'TagCrudController');

Make generated code cleaner

I think it is better to strip comment inside generated code since it already explained in docs. Also generated code are not PSR2 compliant. I can submit pull request if this suggestion approved

[Bug] Call to undefined method App\User::identifiableAttribute()

I created an AgentCrudController with a setupCreateOperation() including fields with related entries.

The Agent class belongsTo the App\User class through the user_id and belongsTo the App\Models\Country class through the country_id

User class implements the public function agent() with hasOne
Country class implements the public function agents() with hasMany
Agent class implements both public function user() and public function country() with belongsTo

The code:

`protected function setupCreateOperation()
{
CRUD::setValidation(JudgeRequest::class);

	/*$this->crud->addField(
        [
            'name' => 'user_id',
            'attribute' => 'name'
        ]
    );*/
    CRUD::field('user_id')->attribute('name');
    CRUD::field('country_id')->attribute('country');

...`

This gives me a Call to undefined method App\User::identifiableAttribute() error on proceeding to Add an Agent.

Tested workarounds:

  1. Use the addField method as shown in the above code
  2. Creating the identifiableAttribute() in the User model

I mention the Country relationship because that one works perfectly using fluent syntax without resorting to the addField() method.

Am I missing something in the fluent syntax?

Latest versions Laravel + Backpack + Windows 10 + VSC

[Feature] Publish field/button/column command

Copied from Laravel-Backpack/CRUD#171

If overwriting fields/buttons/columns happens a lot, it would help if we had a command to take the standard blade file and place it in the correct directory, like /resources/views/vendor/backpack/crud/fields.

The command could look something like:

php artisan backpack:overwrite-field --name=select2
php artisan backpack:overwrite-column --name=date
php artisan backpack:overwrite-button --name=preview

But again - this might not be an actual issue. Do people actually overwrite fields/columns/buttons a lot?

[4.1.0] undefined function Backpack\Generators\Console\Commands\str_plural()

Bug report

What I did

fresh installation, first model creation:

php artisan backpack:crud objekt

What I expected to happen

it should create model, controller and view files

What happened

`Call to undefined function Backpack\Generators\Console\Commands\str_plural()

at vendor/backpack/generators/src/Console/Commands/CrudControllerBackpackCommand.php:83
79| * @return string
80| */
81| protected function replaceNameStrings(&$stub, $name)
82| {

83| $table = str_plural(ltrim(strtolower(preg_replace('/[A-Z]/', '$0', str_replace($this->getNamespace($name).'\', '', $name))), ''));
84|
85| $stub = str_replace('DummyTable', $table, $stub);
86| $stub = str_replace('dummy_class', strtolower(str_replace($this->getNamespace($name).'\', '', $name)), $stub);
`

What I've already tried to fix it

??

Backpack, Laravel, PHP, DB version

all latest, it's new project

When I run ```php artisan bac### PHP VERSION:
PHP 7.3.15-3+ubuntu19.10.1+deb.sury.org+1 (cli) (built: Feb 23 2020 07:24:02) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.15, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.3.15-3+ubuntu19.10.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

LARAVEL VERSION:

v7.3.0@36d8958b5b8058ef0641806e490f91102fdea70d

BACKPACK VERSION:

4.1.x-dev@02bf0a23ebfb81578604a0c89880f13468f1574a
kpack:version``` the output is:

CRUD syntax option in CLI (choose array or fluent)

Hi @tabacitu

I just start my day by creating new CRUD and I noticed a important change in my Controller : the fluent syntax.
It's very interesting but maybe an option for the fluent syntax might be great aswell ?

I explain my case :
My entire project is based on the classic syntax and to stay coherent it would be interesting to set the generator on fluent OR classic by default and add and option to get the Controller with the fluent syntax.

Example :
php artisan backpack:crud <entity_name> --fluent

It's currently not very impactful but when you switch from a controller to another that surprises a bit ๐Ÿ˜„

Mamat

[Bug] Problem adding CrudTrait to existing Model

Bug report

What I did

After building a draft.yml for the Customer model:

php artisan blueprint:build 
php artisan backpack:crud Customer

What I expected to happen

I expected
(1) the CrudTrait to be added to the existing Model, and
(2) the setUpCreateOperation() and setUpListOperation() to be filled in.

What happened

PS C:\Apps\xampp\htdocs\cofour-intern>  php artisan blueprint:build 
...
PS C:\Apps\xampp\htdocs\cofour-intern> php artisan backpack:crud Customer     
Controller created successfully.

   ErrorException 

  Undefined variable: position

  at C:\Apps\xampp\htdocs\cofour-intern\vendor\backpack\generators\src\Console\Commands\CrudModelBackpackCommand.php:94
    90|                     // the same as the array index - arrays start counting from 0,
    91|                     // IDEs start counting from 1
    92| 
    93|                     // add CrudTrait
  > 94|                     array_splice($file_array, $position, 0, '    use \\'.$this->crudTrait.';');
    95| 
    96|                     // save the file
    97|                     $this->files->put($path, implode(PHP_EOL, $file_array));
    98| 

  1   C:\Apps\xampp\htdocs\cofour-intern\vendor\backpack\generators\src\Console\Commands\CrudModelBackpackCommand.php:94
      Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Undefined variable: position", "C:\Apps\xampp\htdocs\cofour-intern\vendor\backpack\generators\src\Console\Commands\CrudModelBackpackCommand.php")

  2   C:\Apps\xampp\htdocs\cofour-intern\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:33     
      Backpack\Generators\Console\Commands\CrudModelBackpackCommand::handle()
PS C:\Apps\xampp\htdocs\cofour-intern> 

What I've already tried to fix it

I manually added use Backpack\CRUD\app\Models\Traits\CrudTrait; to the model, and use CrudTrait; to the class body, which auto-generated the proper files (expectation 1), but does not fill out the setUpOperations (expectation 2).

Also described here on Stackoverflow.

Backpack, Laravel, PHP, DB version

When I run php artisan backpack:version the output is:

### PHP VERSION:
PHP 7.4.7 (cli) (built: Jun  9 2020 13:36:15) ( ZTS Visual C++ 2017 x64 )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies

### LARAVEL VERSION:
v7.19.0@67d6d9688122dcf6c449b74ddc873fc9934e81e6

### BACKPACK VERSION:
4.1.14@f4a6ad91f2aa3760ffe963c5cd87d2b533803323 

Merge Generators into Base

For simplicity, I think backpack/base should include all generators functionality.
It's never been used outside it anyway.

OR

We should require it and install it by default with backpack/base, once the installer is ready.
But that might take some time.

I vote include it in Base. @cristiantone , what say you?

Your requirements could not be resolved to an installable set of packages

Bug report

Using version ^2.0 for backpack/generators
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for backpack/generators ^2.0 -> satisfiable by backpack/generators[2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.0.5, 2.0.6, v2.0.7].
- Can only install one of: backpack/crud[4.0.x-dev, 4.1.x-dev].
- Can only install one of: backpack/crud[4.0.x-dev, 4.1.x-dev].
- Can only install one of: backpack/crud[4.0.x-dev, 4.1.x-dev].
- Conclusion: install backpack/crud 4.0.x-dev
- Installation request for backpack/crud 4.1.x-dev -> satisfiable by backpack/crud[4.1.x-dev].

What I did:

composer require backpack/generators --dev

What I expected to happen:

php artisan backpack:crud notification

What happened:

uninstall this package to update the backpack to version 4.1, as it did not allow me
Now i want to reinstall and i can't

Backpack, Laravel, PHP, DB version:

PHP VERSION:

PHP 7.2.11 (cli) (built: Oct 10 2018 02:04:07) ( ZTS MSVC15 (Visual C++ 2017) x64 )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

LARAVEL VERSION:

v6.18.3@4e48acfaba87f08320a2764d36c3b6a4a4112ccf

BACKPACK VERSION:

4.1.x-dev@50e4bda7c80da16c69da0bc9ade0aa0e0f9408a3

my file composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.2",
        "backpack/backupmanager": "^2.0.0",
        "backpack/crud": "4.1.x-dev",
        "backpack/permissionmanager": "^5.0",
        "backpack/settings": "^3.0.0",
        "barryvdh/laravel-elfinder": "^0.4.3",
        "cviebrock/eloquent-sluggable": "6.0.*",
        "eduardoarandah/backpacklogviewer": "^1.0",
        "fideloper/proxy": "^4.0",
        "intervention/image": "^2.3",
        "khsing/world": "^0.8.0",
        "lab404/laravel-auth-checker": "^1.6",
        "laravel/framework": "^6.0",
        "laravel/helpers": "^1.1",
        "laravel/tinker": "^2.0",
        "wildside/userstamps": "^1.1"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.3",
        "facade/ignition": "^1.16",
        "nunomaduro/collision": "^3.0",
        "phpunit/phpunit": "^8.5",
        "fzaninotto/faker": "^1.4",
        "laracasts/generators": "^2.0",
        "mockery/mockery": "^1.0"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

[BUG] backpack:build copy found models in other directories (e.g. app/packages) into `app/Models` .

Bug report

What I did:

I have some local packages (Models, Controllers etc) inside app/packages folder.

When running php artisan backpack:build it find those models too. Problem is not finding them, is the fact the backpack copy them into app/Models folder.

This makes me also think we should have some key in config where we could add an array of locations to ignore searching for models.

What I expected to happen:

Atmost, find the models and add the CrudTrait. Never copy them!

What happened:

My models were copied into app/Models

What I've already tried to fix it:

Backpack, Laravel, PHP, DB version:

Laracasts Generators issue making a migration

After install on Laravel 5.5 continue to receive this error when trying to create a migration:

php artisan make:migration:schema create_tags_table --schema="name:string:unique" --model=0

Method Laracasts\Generators\Commands\MigrationMakeCommand::handle() does n
ot exist

Domain used for packagist is not the same.

For all other packages we've used:
backpack/base
backpack/logmanager
etc

And you've used:
laravel-backpack/generators

Let's change it to backpack - since it's available, the shorter the better here. Plus, we'd like everyone to associate the "backpack" name with this project - Laravel Backpack is just on Github because Backpack was taken.

Suggestion: use PHP-parser library for code generation

Hello everyone.

I have a proposition about Backpack CRUD generators implementation.
Instead of using ".stub" files and template-based file generation you can use a PHP-parser project for generate class abstract syntax tree: https://github.com/nikic/PHP-Parser/blob/master/doc/4_Code_generation.markdown

I think this is a definitely better way for code generation, because of several reasons:

  • PHP-parser more configurable - you can add any number of additional arguments as you want
  • you will not generate code that you don't need (no more commented parts of code that are usually deleted after generation)
  • you can configure code style of generated code (currently code in all generated classes differs from my project codestyle and I have to reformat them)
  • you can add support of external Laravel plugins much easier (I use Eloquence for all my models, and I need to add all traits and options to every generated model manually)
  • you will never have a syntax errors in code generated from abstract syntax tree
  • AST generator can rely on table/model structure, CLI user input or Backpack configuration files and will always represent actual project structure
  • docblock-comments can also be generated via AST
  • you can even modify existing (already generated) classes instead of manually rewriting code. Think of it as of some kind of automated refactoring operation
  • and finally, code generation is not like text or markup generation - so we need to use a different approach for this task

Backpack generators have not very large codebase now, and I think this is not too late to switch form template-based generation to AST-based generation.

I like Backpack project and I think it deserves a really good code generation support.
Any feedback or discussion are welcome.

Allow stubs to be taken from a different location

Hi,

I'd like to be able to use my own stubs -- obviously based on the ones you already have. It makes sense to update getStub so that it checks either if stubs are stored in a different location, or accept an argument allowing you to pass a directory where the stubs are located.

Thanks.

[Bug] Cannot run "php artisan backpack:crud bug" working with Bug.php model

ErrorException

Undefined offset: 1

at C:\wamp64\www\toplitz\vendor\backpack\generators\src\Console\Commands\CrudModelBackpackCommand.php:84
80โ–• if (Str::contains($line, $classDefinition)) {
81โ–• if (Str::endsWith($line, '{')) {
82โ–• // add the trait on the next
83โ–• $position = $key + 1;
โžœ 84โ–• } elseif ($file_array[$key + 1] == '{') {
85โ–• // add the trait on the next next line
86โ–• $position = $key + 2;
87โ–• }
88โ–•

1 C:\wamp64\www\toplitz\vendor\backpack\generators\src\Console\Commands\CrudModelBackpackCommand.php:84
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Undefined offset: 1", "C:\wamp64\www\toplitz\vendor\backpack\generators\src\Console\Commands\CrudModelBackpackCommand.php")

2 C:\wamp64\www\toplitz\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:37
Backpack\Generators\Console\Commands\CrudModelBackpackCommand::handle()

Wrong namespace of generated classes

Bug report

The generated files do not take the app name into account for the Request classes in the use lines in the Controller

What I did:

Generated the crud for a model

What I expected to happen:

The crud to work as expected

What happened:

Exception: Class App\Http\Requests\xxxRequest does not exist

What I've already tried to fix it:

Backpack, Laravel, PHP, DB version:

backpack/generators: 1.1.11

Dependency Issue

Bug report

D:\xampp\htdocs\aayo\aayowebapp>composer require phpoffice/phpspreadsheet --update-no-dev
You are running Composer with SSL/TLS protection disabled.
Using version ^1.13 for phpoffice/phpspreadsheet
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package backpack/generators (locked at v2.0.7, required as ^3.0) is satisfiable by backpack/generators[v2.0.7] but these conflict with your requirements or minimum-stability.

Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.

Installation failed, reverting ./composer.json to its original content.

What I did:

I tried to install PHPspreadsheet and its giving me this error

What I expected to happen:

What happened:

What I've already tried to fix it:

Backpack, Laravel, PHP, DB version:

Backpack: 4.1
PHP: 7.3

Cannot create a migration when following the getting started tutorial without errors

Bug report

What I did:

Ran the command php artisan make:migration create_tags_table --schema="name:string:unique,slug:string:unique"

What I expected to happen:

the migration to be created for a Tag entity

What happened:

Got this error
There are no commands defined in the "make:migration" namespace.

Did you mean this?
make

What I've already tried to fix it:

just cleared cache, autoload dump

Backpack, Laravel, PHP, DB version:

Backpack: latest 4.x
Laravel: 7.10.3
DB version: 5.7.29-0ubuntu0.18.04.1

[Feature Request] Command to delete a crud

Feature Request

What's the feature you think Backpack should have?

A command that does the opposite of php artisan backpack:crud.
Quickly remove files and content added by php artisan backpack:crud in case you added a crud by mistake or had a typo

[4.1.x][Feature] Command to generate CRUDs for all models

I see no reason why we would not create a command that:

  • searches for all Models (classes that extend Eloquent, directly or indirectly) in app/Models (or a different folder if you pass a parameter
  • for each model individually:
    • adds CrudTrait (if it's not already used)
    • runs php artisan backpack:crud (if a CRUD does not already exist for it)

That means that you can build your Laravel app like you normally would (including the models), without even thinking about your admin panel, and when you're done with the app, you'll just do:

composer require backpack/crud:"4.1.*"
composer require backpack/generators --dev
php artisan backpack:install
php artisan backpack:build

It would spit out CRUDs for all your models, which is what you probably intended anyway. Of course, you'd need to go through each generated CRUD and personalise it, but it would be very very useful to have this one command that generates all the CRUDs you need. And impressive ๐Ÿ˜„

Extra features:

  • --i or --interactive flag, so that it asks you for each Model if you want to build a CRUD for it (that way you can skip the ones you want);
  • --path='app' to change the path to your Models folder;

Command name - I'm not sure what a good one would be. I'm thinking:

  • php artisan backpack:build
  • php artisan backpack:generate (a little too broad)
  • php artisan backpack:initialize

I'm not 100% happy with any of them. I'm open to suggestions.


Thoughs? Anyone else excited about having this, like I am? ๐Ÿ˜„

[Proposal] Remove commands that are not backpack-specific

Currently we have:

  // backpack-specific
  backpack:chart                Create a ChartController and route
  backpack:chart-controller     Generate a Backpack ChartController
  backpack:config               Generate a backpack templated config
  backpack:crud                 Create a CRUD interface: Controller, Model, Request
  backpack:crud-controller      Generate a Backpack CRUD controller
  backpack:crud-model           Generate a Backpack CRUD model
  backpack:crud-operation       Generate a Backpack CRUD operation trait
  backpack:crud-request         Generate a Backpack CRUD request

  // not backpack specific
  backpack:model                Generate a backpack templated model
  backpack:request              Generate a backpack templated request
  backpack:view                 Generate a backpack templated view

I don't see a reason why we would keep the last 3. I'm pretty sure nobody uses them anyway, since Laravel has its own make commands for them nowadays.

I think it's about time we remove those commands and their stubs.

Using BackPack with nwidart/laravel-modules

Bug report

What I did:

I am trying to set up a Web application that has a huge number of models in Laravel/BackPack. To simply dump all the models into \App would be total chaos. Making the transition from Yii2, the nwidart/Laravel-modules approach seemed to be the best approach since it would allow me to create as many modules as I needed, thus keeping the number of models in any given module down to a manageable number. Laravel-modules creates a directory named \Modules at the same level as \Modules then has subdirectories for each module, such as \Modules\Network. Each module then has subdirectories for Config, Console, Database, Entities, Http, Providers, Resources, Routes, and Tests, thus paralleling the structure of the main app. Each module is very much like a package in that it could easily be pulled out of one Laravel application and put into another with minimal effort.

Working from that starting point, I looked everyplace I could think of to find how to specify a path in the BackPack CRUD generator and couldn't come up with anything. I then tried issuing the following Artisan command:

php artisan backpack:model \Modules\Network\NetworkDevice --softdelete

In this case, I already had a module, named Network created by Laravel-Modules. I was trying to create a model for the network_devices table.

What I expected to happen:

I expected to have the model generator place a NetworkDevice model in the directory \Modules\Network directory with the namespace Modules\Network.

What happened:

The model generator created a directory structure like this: \App\Modules\Network and put the NetworkDevice.php file in it with the namespace App\Modules\Network.

What I've already tried to fix it:

Since I am unable to find any documentation on how to provide a modular organization in BackPack,I am at a loss on how to proceed.

Backpack, Laravel, PHP, DB version:

BackPack: ver. 3.5
Laravel: ver. 5.7.20
PHP: ver. 7.2.10
DB: MariaDB ver. 10.1.36

I'm really hoping that BackPack will be able to handle complex Web applications. I really like what I've seen of it thus far, although I must say that I am totally dismayed at the inability of Laravel, in general, to handle master-detail forms, a totally ubiquitous part of any contemporary Web application. Surely, BackPack can handle something as normative as modularizing.

backpack:build does not take models in Models folder

The backpack:build does not look into the app/Models directory when trying to get models

What I did:

Laravel 8 project
php artisan backpack:build

What I expected to happen:

that the models in app/Models was processed

suggestion: an extra parameter to override the base_path() / app parameter

What happened:

output: no models found and no CRUD's were created

What I've already tried to fix it:

Backpack, Laravel, PHP, DB version:

backpack/crud 4.1.30
backpack/generators v3.1.5
Laravel v8.22.1
PHP v7.4.5

MassAssignmentException in Model.php

First of all, I really love Backpack, especially the CRUD package. Great work.

I was under the impression that, when using the generators, the new CRUD would work out of the box. But when I test it, using the example from the Docs, I get an exception:

MassAssignmentException in Model.php line 444:
name

When I look at the Model that was created, I see that the fillable is still commented out.
Is this intended behaviour? Should I edit the Model, the Controller and the Request manually?
Or am I doing something wrong?

Any help would be greatly appreciated

[4.1.x][Feature] Easily share or use other people's fields, columns, filters, CRUDs

Continuing my rant in Laravel-Backpack/CRUD#1724

Status: If you want to share a field with the community, you can do so by forking/cloning this example project, and following the steps in this tutorial that I've just finished yesterday.

The Problem: It still takes quite a long time - especially if you only want to share one file with the world. I'd say at least 15 minutes if you've done it before, but it can be up to 30-45 minutes if you've never created a package, put it on Packagist, or even have a Github account. You have to first understand how it works.

Solution 1

We could make it faster to create the package, by creating a CLI to generate the package you want, with the right namespace, vendor name, package name, author info, everything. It could work something like this:

$ php artisan backpack:package

# PACKAGE NAME. What do you want to call the package? (use kebab-case, for ex: toggle-field-for-backpack)
> _

# VENDOR NAME. What namespace/vendor-name do you want to release this under? (Usually it's your github username, or your company's github username; Use kebab-case, for ex: vendor-name/toggle-field-for-backpack)
> _

# CLASS NAMESPACE. Where do you want the namespace for your PHP classes to be? (It's a good idea to use VendorName\PackageName - only change if you know what you're doing; Use PascalCase)
> VendorName\PackageName # calculate default from the above

# AUTHOR NAME. What's your name? (ex: Cristian Tabacitu)
> _

# AUTHOR EMAIL. What's your email? This will be punched in people to be able to send you emails for security issues, instead of discussing them in the open (ex: [email protected])
> _

# AUTHOR WEBSITE. What's your website? (Use a full URL, for ex: https://tabacitu.ro)
> _

# ADDON TYPE. What custom thing do you want to share with this package? Options: field, column, filter, button, crud
> _

# FIELD NAME. You've chosen to share a field, which is just one file - we can help generate almost _everything_. What's the name of that file? (we'll assume that file is already in resources/views/vendor/backpack/crud/fields, and has a .blade.php extension; you just need to type the field name - for ex: improved_phone)
> _

# Thank you!
#
# 10% - Copy-pasting the necessary files to packages/vendor-name/package-name
# 20% - Replacing vendor name
# 30% - Replacing package name
# 40% - Replacing class namespace 
# 50% - Replacing author name
# 60% - Replacing author email
# 70% - Replacing author website
# 80% - Copying view
# 90% - Initializing git
# 95% - Committing the initial code to git
# 100% - Done!
#
# To do:
# 1. Go to packages/vendor-name/package-name and make sure everything's ok.
# 2. Change the README.md file to include the description and instructions for _your_ field.
# 3. Commit your changes.
# 4. Tag the release as 1.0.0
# 5. Create a new Github repo and push the code in packages/vendor-name/package-name
# 6. Submit your Github repo to Packagist.org
# 7. Add a screenshot to your README.md
# 8. Install the package in your project, test it, fix it. Remember to tag a final stable release.
# 9. Ask for feedback on subreddit & Gitter.
# 10. Promote your new package!

Solution 2

Instead of putting the custom fields/columns/everything on Packagist, we could... host our own directory. Where the people could just post that one file, and people would be able to just download it and put it inside their project. That would be much easier, but developers wouldn't be able to push updates and bug fixes... Food for thought...

Should open files in IDE

If a user has something like this in his .env file:

APP_EDITOR=subl

We can be pretty sure that:

  • he knows about Laravel's trick to open files after php artisan make:smth;
  • we wants to open the files immediately after generation;

No other reason that .env value would be there.

If we're so certain that's what he wants. Let's do it. If that's present, open the generated files in the editor of choice, after they're generated.

It should be as simple as:

// open the file in the preferred editor
if (env('APP_EDITOR')) {
   exec(env('APP_EDITOR').' '.$filePath);
}

Missing $request parameter

When manipulation the $request in the storeor update methods of a CrudController and you don't inject it to the parent methods, your manipulations are not present.

As this happens to me far too many times (and there was currently a question in Gitter) I would suggest add the $request paramter to the parent::storeCrud() call and parent::updateCrud()call in the Controller template.

Currently this looks like:

    public function store(StoreRequest $request)
    {
        // your additional operations before save here
        $redirect_location = parent::storeCrud();
        // your additional operations after save here
        // use $this->data['entry'] or $this->crud->entry
        return $redirect_location;
    }

    public function update(UpdateRequest $request)
    {
        // your additional operations before save here
        $redirect_location = parent::updateCrud();
        // your additional operations after save here
        // use $this->data['entry'] or $this->crud->entry
        return $redirect_location;
    }

and would be changed to

    public function store(StoreRequest $request)
    {
        // your additional operations before save here
        $redirect_location = parent::storeCrud($request); // inject the request instance
        // your additional operations after save here
        // use $this->data['entry'] or $this->crud->entry
        return $redirect_location;
    }

    public function update(UpdateRequest $request)
    {
        // your additional operations before save here
        $redirect_location = parent::updateCrud($request); // inject the request instance
        // your additional operations after save here
        // use $this->data['entry'] or $this->crud->entry
        return $redirect_location;
    }

Request: backpack:crud-model to generate migration

Love the work you've done so far, is much appreciated :)

Im starting to have a little dig around, and wondered what the possibility of adding the migration creation to the model generation?

For example a normal artisan command would be php artisan make:model Cake --migration and you'd get a migration with it.

Would this functionality be possible to add (or does it already exist?)

Many thanks for your hard work.

Owen

MassAssignmentException in laravel CRUD operation

Bug report

MassAssignmentException

What I did:

while updating the user status above error thrown.

What I expected to happen:

status should be updated

What happened:

MassAssignmentException is thrown

What I've already tried to fix it:

Backpack, Laravel, PHP, DB version:

Laravel 5.4,phpmyadmin

Models in Top level directory recreated in model sub folder

Bug report

What I did

php artisan backpack:crud Product

What I expected to happen

I expected it to use the models from the top level directory

What happened

The crud command created a new Product model in the models directory and attached new controller to that empty model

What I've already tried to fix it

I looked through the config file assuming that this is some sort of preset which can be changed to specify the location of the models, but didn't find such a setting.

Backpack, Laravel, PHP, DB version

PHP 7.4.8 (cli) (built: Jul 9 2020 23:43:51) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Xdebug v2.9.6, Copyright (c) 2002-2020, by Derick Rethans
with Zend OPcache v7.4.8, Copyright (c), by Zend Technologies

LARAVEL VERSION:

v7.25.0@fdf3d4a40447eb286ba3820768306cae64bcc0b3

BACKPACK VERSION:

4.1.17@952ba942c7ff8b41fc2409d3c3cfef68dd48bf18

[v12][Feature] php artisan backpack:crud - command should become interactive

More details in my comment here - #41 (comment)

I'll copy-paste the gist of it:


Generated controllers use setFromDb() which is a nightmare - it works, but we can't push any updates to it without breaking people's apps. A better way to proceed would be to generate actual addField() and addColumn() code. We can modify and tweak that every day, and not break people's apps. In time, we would deprecate setFromDb() and I'll be able to sleep at night :-) Solves that problem.

I see this php artisan backpack:crud command becoming more interactive & customizable than the current one, here's how I see the command and interaction:

php artisan backpack:crud 
#notice: no extra parameters; you don't have to remember if it's singular, plural, etc; just the command, which is simple to remember or can even be php artisan make:crud, but that would break the backpack convention

> ----------------------
> | Making  a new CRUD |
> ----------------------
> Please answer a few questions:
> 
> What is the TABLE NAME? (ex: products; db table where your entries are stored) 

tags

> What is your entity name, in PLURAL? (ex: products; used for showing buttons like Edit Products)

tags #sensible default is provided, just have to hit Enter most of the times

> What is your entity name, in SINGULAR? (ex: product; used for showing buttons like Add Product)

tag  #sensible default is provided, just have to hit Enter most of the times

> What you like to generate a ROUTE in routes/backpack/custom.php?

yes #defaults to yes, just have to hit Enter most of the times

> What you like to add a SIDEBAR ITEM in resources/views/vendor/backpack/base/inc/sidebar_content.blade.php?

yes #defaults to yes, just have to hit Enter most of the times

> What ICON would you like it to have?

fa fa-list #defaults to something, anything

> Would you like to open the files after generation? If so, please type your IDE handle (ex: subl, pstorm, vscode)

no #defaults to no

> --------------
> | Thank you! |
> --------------
> Generated App\Models\Tag.php
> Generated App\Http\Requests\TagRequest.php
> Generated App\Http\Controllers\Admin\TagCrudController.php
> Added route in config/backpack/custom.php
> Added sidebar item in resources/views/vendor/backpack/base/inc/sidebar_content.blade.php
> ------------------------
> Done! Please take a look at the generated files and modify as you like.
> ------------------------

Additionally we could have a long list of questions, for all kinds of customizations, but with a different flag, for example php artisan backpack:make:crud --verbose:

> [OPTIONAL] Where would you like the Model to be generated? (model namespace)

App\Models #sensible default is provided, just have to hit Enter most of the times

> [OPTIONAL] Where would you like the CrudController to be generated? (controller namespace)

App\Http\Controllers\Admin #sensible default is provided, just have to hit Enter most of the times

> [OPTIONAL] Where would you like your Request to be generated? (request namespace)

App\Http\Requests #sensible default is provided, just have to hit Enter most of the times

But that's less important. What I do think is important is that we do this AT THE RIGHT TIME. And I think that's when we render setFromDb() obsolete. Which I've been dying to do for a long long time - since we can't push any updates to it, ever, or we'd break people's apps. A better way to do the same thing as setFromDb() would be to generate actual addField() and addColumn() code, based on the table.

To make it a non-breaking change, we could:

  • stick to the current behaviour if the parameter is passed;
  • use this new interactive behaviour if NO parameter is passed, or if the --i flag is used;

Installation fails with "syntax error, unexpected '$kebabName' (T_VARIABLE), expecting ']'"

Bug report

What I did:

Ran composer require backpack/generators --dev as part of the installation instructions

What I expected to happen:

The package installs without error.

What happened:

Received error:

syntax error, unexpected '$kebabName' (T_VARIABLE), expecting ']'

Full command output:

$ composer require backpack/generators --dev
Using version ^3.1 for backpack/generators
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing backpack/generators (v3.1.2): Loading from cache
Writing lock file
Generating optimized autoload files
ocramius/package-versions: Generating version class...
ocramius/package-versions: ...done generating version class
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

   ParseError 

  syntax error, unexpected '$kebabName' (T_VARIABLE), expecting ']'

  at vendor/backpack/generators/src/Console/Commands/ChartBackpackCommand.php:41
    37|         echo Artisan::output();
    38| 
    39|         // Create the chart route
    40|         Artisan::call('backpack:add-custom-route', [
  > 41|             'code' => "Route::get('charts/".$kebabName."', 'Charts\\".$studlyName."ChartController@response')->name('charts.'."$kebabName".'.index');",
    42|         ]);
    43|         echo Artisan::output();
    44|     }
    45| }

      +1 vendor frames 
  2   [internal]:0
      Composer\Autoload\ClassLoader::loadClass("Backpack\Generators\Console\Commands\ChartBackpackCommand")

  3   [internal]:0
      spl_autoload_call("Backpack\Generators\Console\Commands\ChartBackpackCommand")
Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Installation failed, reverting ./composer.json to its original content.

What I've already tried to fix it:

I created a fresh laravel app (using composer ...) and tried to only install backpack following the installation instructions. I got the same error on the fresh install.

Backpack, Laravel, PHP, DB version:

  • backpack/crud: 4.1.11
  • backpack/generator: v3.1.2
  • Laravel: v7.16.1
  • PHP 7.3.17
  • DB: 5.7.30

Working on this now. I believe I found the fix, so I should have a PR open later today.

Seems someone else is working on it already: #92

Add reference to CrudPanel for code completion

Bug report

In PHPStorm, no code is suggested when using $this->crud in a controller.

What I did:

Typed $this->crud in a CrudController, whilst using the Fields API.

What I expected to happen:

The IDE should have hinted at any methods or properties available.

What happened:

Nothing was hinted at.

What I've already tried to fix it:

Added a reference to the CrudPanel class (use Backpack\CRUD\CrudPanel;). This allows for typehinting

Backpack, Laravel, PHP, DB version:

Generators version 1.2.5
PHP 7.2
Laravel 5.7

Permission on field.

Hi, I wanted to know how I can set permissions on fields.
I have the account model with field1, field2, field3 and field4.
I want to set that user A can see field1, field2 but can not change field3 and field4 does not see it right.
It would be possible ?

Thanks.

Generated models should have $fillable and relationships

After you run php artisan backpack:crud tag for example, it would be great if you did NOT have to go through the model to edit it. I found myself doing this for two reasons:

  1. $fillable did not include the fields, and I like to use $fillable rather than $guarded;
  2. The relationships are not defined;

[anyone, please specify more reasons if you have them]

I think automating these tasks for the developer will make it a little faster to develop CRUDs. And I think we can achieve them both:

  1. $fillable can be filled with every column in the db (except the primary key, created_at, updated_at and deleted_at);
  2. The relationships can be determined using the foreign keys you've set in the db. This would also promote a good practice that MySQL users ignore (using foreign keys).

A few links that might help:

[Bug] crud building breaks at model creation on Windows OS

When running any of the following commands:

php artisan backpack:build
or
php artisan backpack:crud XYZ
or
php artisan backpack:crud-model XYZ

execution breaks with
Undefined offset: 1
at [local_laravel_path]\vendor\backpack\generators\src\Console\Commands\CrudModelBackpackCommand.php:84

I'm running a fresh install with Laravel 7 + Backpack on Windows 10 x64 with Visual Studio Code
All latest versions.

It turns out CrudModelBackpackCommand.php on line 65 uses the infamous explode using PHP_EOL with known bad results on some Windows environments. Unfortunately mine included.

So replacing line 65:
$file_array = explode(PHP_EOL, $file);
with:
$file_array = preg_split('/\n|\r\n?/', $file);

resolves this issue.

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.