Giter Site home page Giter Site logo

digitaldreams / laracrud Goto Github PK

View Code? Open in Web Editor NEW
329.0 22.0 54.0 4.84 MB

Laravel Code Generator based on MySQL Database

License: MIT License

PHP 95.73% Blade 4.27%
php laravel-crud laravel-5-package laravel-framework crud-generator laracrud laravel code-generator laravel-application

laracrud's Introduction

Laravel Code Generator

Do you have a well structed database and you want to make a Laravel Application on top of it. By using this tools you can generate Models which have necessary methods and property, Request class with rules, generate route from controllers method and its parameter and full features form with validation error message and more with a single line of command. So lets start. See demo code and slides

Installation

composer require digitaldream/laracrud --dev

Setting

  1. Add this line to config/app.php providers array . Not needed if you are using laravel 5.5 or greater
    LaraCrud\LaraCrudServiceProvider::class
  1. Then Run
    php artisan vendor:publish --provider="LaraCrud\LaraCrudServiceProvider"

Commands

Then you can see new commands by running 'php artisan'

  • laracrud:model {tableName} {name?} {--on=} {--off=}: Create model based on table
  • laracrud:request {Model} {name?} {--resource=} {--controller=} {--api}: Create Request Class/es based on table
  • laracrud:Controller {Model} {name?} {--parent=} {--only=} {--api}: Create Controller Class based on Model
  • laracrud:mvc {table} {--api}: Run above commands into one place
  • laracrud:route {controller} {--api}: Create routes based on controller method
  • laracrud:view {Model} {--page=(index|create|edit|show|form|table|panel|modal)} {--type=} {--name=} {--controller=}
  • laracrud:migration {table}: Create a migration file based on Table structure. Its opposite of normal migration file creation in Laravel
  • laracrud:policy {model} {--controller=} {--name=}
  • laracrud:package {--name=}
  • laracrud:transformer {model} {name?}: Create a dingo api transformer for a model
  • laracrud:test {controller} {--api}: Create test methods for each of the method of a controller

N.B: --api option will generate api resource. Like Controller, Request, Route, Test. Dingo API compatible code will be generated . See API documentation

How to Use

Create a Model

There are some good practice for model in Laravel. Use scope to define query, define fillable, dates, casts etc. Also define relation, setAttribute and getAttribute for doing work before and after model save and fetch.

We are going to create this thing automatically by reading table structure and its relation to others table.

    php artisan laracrud:model users

By default Model Name will be based on Table name. But Model name can be specified as second parameter. Like below

php artisan laracrud:model users MyUser

Video Tutorial

Create Request

A well structured table validate everything before inserting . You can not insert a illegal date in a birth_date column if its data type set to date.So if we have this logic set on table why we should write it on Request again. Lets use this table logic to create a request class in laravel.

php artisan laracrud:request MyUser

Here MyUser is Eloquent Model. From LaraCrud version 4.* this command accept Model Name instead of Table

Like Model Name we can also specify a custom request name.

php artisan laracrud:request User RegisterRequest

Also If you like to create multiple request for your resourceful controller then

php artisan laracrud:request User –-resource=index,show,create,update,destroy

It will create a folder users on app/Http/Requests folder and create these request classes. Sometimes you may like to create individual request class for each of your controller method then.

php artisan laracrud:request User –-controller=UserController
php artisan laracrud:request User --controller=UserController --api //this will generated Request for API usages

It will read your controller and create request classes for your Public method

video tutorial

Create Controller

    php artisan laracrud:controller User
    //Or Give a controller name.
    php artisan laracrud:controller User MyUserController
    //Or we can give a sub namespace
    php artisan laracrud:controller User User/UserController
    //It will create a folder User to controllers
    php artisan laracrud:controller Comment --parent=Post // it will create a sub resource CommentController

This will create a controller which have create, edit, save and delete method with codes . It also handle your relation syncronization

video tutorial

Create View

A typical form represent a database table. E.g. for a Registration form it has all the input field which is necessary for users table. Most of the time we use Bootstrap to generate a form . It has error field highlighting if validation fails. Also display value. This all can be done by

 php artisan laracrud:view User --page=form
 php artisan laracrud:view User --page=index --type=panel //There are three type of layout for index page panel,table and tabpan
 php artisan laracrud:view User --controller=UserController // Create all the views which is not created yet for this controller
 

Here User is Eloquent Model. From LaraCrud version 4.* this command accept Model Name instead of Table

This will create a complete users crud view.

video tutorial

Create Route

Routes are the most vital part of a laravel application. WE create routes by its public methods and parameter. Lets do this work to rotue command.

    php artisan laracrud:route UserController
    php artisan laracrud:route UserController --api // generate api routes for this conroller

If you have some routes already redine for then do not worry. It will create routes for which does not define yet. Please use forward slash(/) for sub namespace. For example,

 php artisan laracrud:route Auth/AuthController

Policy

Laravel have default policy generator. It works like same with one extra feature that is create policy method based on controller public methods.

php artisan laracrud:policy User 
// will create policy class with basic methods
php artisan laracrud:policy User --controller=UserController
// create method based on Controller public methods

Package

Packages gives us opportunity to create/use components into our existing application. That make our code reusable. Laravel package has similar structure as a Laravel application has.

php artisan laracrud:package Hello

This will create a folder same structure as a Laravel application has into your /packages folder See Package documentation Video tutorial

Test

We need to test our routes endpoints. To create test class based on a controller do the following

php artisan laracrud:test UserController
// or to make api test just pass --api like below
php artisan laracrud:test UserController --api

Transformer

Transformer are a vital part of Dingo API. To expose a model to api endpoint Transformer play media between api and model.

php artisan laracrud:transformer User

See API documentation

Create everything at once

If we need all the command to then just to

    php artisan laracrud:mvc users
    php artisan laracrud:mvc users --api // create all the API related resources

It will create Model, Request, Controller, View. Then you just need to run route command to create routes.

Migration

Somethings we may need to create a migration file from a table. Then this command will be useful. It will generate all the necessary code for your migration files. So your migration file is ready to use.

php artisan laracrud:migration users

Customize Code Template

Coding Style differ from developer to developer. So you can control how your code will be generated. Code templates are organized by folder in resources/vendor/laracrud/templates . Go there and change the style. After that your code will be generated by reading these files. Please do not remove or change @@placeHolder@@. This will be replaced by application.

NB: only for mysql database

It is recommended to take a look in the generated file before use it.

Like my work? If so hire me on upwork

laracrud's People

Contributors

digitaldreams avatar rap2hpoutre avatar zhouyixiang avatar

Stargazers

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

Watchers

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

laracrud's Issues

Undefined property: App\Models\.... on line 101 in ...\lluminate\Database\Eloquent\Relations\BelongsTo.php

With the command

php artisan laracrud:controller Issuance --api

I'm getting the error:

Undefined property: App\Models\Issuance::$weeklynetorderid on line 101 in C:\xampp2\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\BelongsTo.php

weeklynetorderid is the foreign key pointing to an id column in another table. The function within the Issuance model is

public function weeklynetorderid()
{
    return $this->belongsTo(WeeklyNetorder::class,'weeklynetorderid');
}

I generated WeeklyNetorder model already which is being referred to.

My searches for this error seems to indicate when there is confusion between weeklynetorderid as a function or as a property but it hasn't made a solution clearer to me.

How can I troubleshoot?

Create a demo project

Create a demo project and display all possible option so user can see how this tool can help before using it.

It is compatible with lumen 5.6.+?

It is compatible with lumen 5.6.+?

After add "digitaldream/laracrud": "3.*" on composer.json

composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 5 installs, 2 updates, 24 removals
  - Removing illuminate/console (v5.6.20)
  - Removing illuminate/routing (v5.6.20)
  - Removing illuminate/session (v5.6.20)
  - Removing illuminate/view (v5.6.20)
  - Removing illuminate/validation (v5.6.20)
  - Removing illuminate/translation (v5.6.20)
  - Removing illuminate/support (v5.6.20)
  - Removing illuminate/queue (v5.6.20)
  - Removing illuminate/pipeline (v5.6.20)
  - Removing illuminate/pagination (v5.6.20)
  - Removing illuminate/log (v5.6.20)
  - Removing illuminate/http (v5.6.20)
  - Removing illuminate/hashing (v5.6.20)
  - Removing illuminate/filesystem (v5.6.20)
  - Removing illuminate/events (v5.6.20)
  - Removing illuminate/encryption (v5.6.20)
  - Removing illuminate/container (v5.6.20)
  - Removing illuminate/config (v5.6.20)
  - Removing illuminate/cache (v5.6.20)
  - Removing illuminate/bus (v5.6.20)
  - Removing illuminate/broadcasting (v5.6.20)
  - Removing illuminate/mail (v5.6.20)
  - Removing illuminate/database (v5.6.20)
  - Removing illuminate/auth (v5.6.20)
  - Updating nesbot/carbon (1.27.0 => 1.25.0): Loading from cache
  - Installing digitaldream/dbreader (1.4): Downloading (100%)         
  - Installing paragonie/random_compat (v2.0.12): Loading from cache
  - Installing ramsey/uuid (3.7.3): Loading from cache
  - Installing league/flysystem (1.0.44): Loading from cache
  - Updating laravel/framework (v5.6.20 => v5.6.20): Downloading (100%)         
  - Installing digitaldream/laracrud (3.1.1): Downloading (100%)         
paragonie/random_compat suggests installing ext-libsodium (Provides a modern crypto API that can be used to generate random bytes.)
ramsey/uuid suggests installing ircmaxell/random-lib (Provides RandomLib for use with the RandomLibAdapter)
ramsey/uuid suggests installing ext-libsodium (Provides the PECL libsodium extension for use with the SodiumRandomGenerator)
ramsey/uuid suggests installing ext-uuid (Provides the PECL UUID extension for use with the PeclUuidTimeGenerator and PeclUuidRandomGenerator)
ramsey/uuid suggests installing moontoast/math (Provides support for converting UUID to 128-bit integer (in string form).)
ramsey/uuid suggests installing ramsey/uuid-doctrine (Allows the use of Ramsey\Uuid\Uuid as Doctrine field type.)
ramsey/uuid suggests installing ramsey/uuid-console (A console application for generating UUIDs with ramsey/uuid)
league/flysystem suggests installing league/flysystem-aws-s3-v2 (Allows you to use S3 storage with AWS SDK v2)
league/flysystem suggests installing league/flysystem-aws-s3-v3 (Allows you to use S3 storage with AWS SDK v3)
league/flysystem suggests installing league/flysystem-azure (Allows you to use Windows Azure Blob storage)
league/flysystem suggests installing league/flysystem-cached-adapter (Flysystem adapter decorator for metadata caching)
league/flysystem suggests installing league/flysystem-eventable-filesystem (Allows you to use EventableFilesystem)
league/flysystem suggests installing league/flysystem-rackspace (Allows you to use Rackspace Cloud Files)
league/flysystem suggests installing league/flysystem-sftp (Allows you to use SFTP server storage via phpseclib)
league/flysystem suggests installing league/flysystem-webdav (Allows you to use WebDAV storage)
league/flysystem suggests installing league/flysystem-ziparchive (Allows you to use ZipArchive adapter)
league/flysystem suggests installing spatie/flysystem-dropbox (Allows you to use Dropbox storage)
league/flysystem suggests installing srmklive/flysystem-dropbox-v2 (Allows you to use Dropbox storage for PHP 5 applications)
digitaldream/laracrud suggests installing intervention/image (For Image)
digitaldream/laracrud suggests installing tymon/jwt-auth (For API authentication)
digitaldream/laracrud suggests installing dingo/api (To make API)
Writing lock file
Generating autoload files
marcodasilva@LAPTOP-MADSA01:/data/www/eureka/APJ-api$ php artisan
PHP Fatal error:  Uncaught ReflectionException: Class path.storage does not exist in /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Container/Container.php:767
Stack trace:
#0 /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Container/Container.php(767): ReflectionClass->__construct('path.storage')
#1 /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Container/Container.php(646): Illuminate\Container\Container->build('path.storage')
#2 /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Container/Container.php(601): Illuminate\Container\Container->resolve('path.storage', Array)
#3 /data/www/eureka/APJ-api/vendor/laravel/lumen-framework/src/Application.php(221): Illuminate\Container\Container->make('path.storage', Array)
#4 /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(119): Laravel\Lumen\Application->make('path.storage', Array)
#5 /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(874): a in /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 767

In Container.php line 767:
                                                                                                                                                                    
  Uncaught ReflectionException: Class path.storage does not exist in /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Container/Container.php:767   
  Stack trace:                                                                                                                                                      
  #0 /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Container/Container.php(767): ReflectionClass->__construct('path.storage')                    
  #1 /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Container/Container.php(646): Illuminate\Container\Container->build('path.storage')           
  #2 /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Container/Container.php(601): Illuminate\Container\Container->resolve('path.storage', Array)  
  #3 /data/www/eureka/APJ-api/vendor/laravel/lumen-framework/src/Application.php(221): Illuminate\Container\Container->make('path.storage', Array)                  
  #4 /data/www/eureka/APJ-api/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(119): Laravel\Lumen\Application->make('path.storage', Array)  

Add options --only and --except to get or remove columns

Developer can easily pass which column they need to show in view by passing --only or --except

Like laracrud:model users --only=id,name,email

Or
laracrud:model users --except=remember_token.

Also developer can able to create observer and policy for model by passing --observer and --policy respectively .

Doesn't work on Laravel 7.x, PHP 7.4

# php artisan laracrud:package Laracrud
mkdir(): No such file or directory on line 67 in /application/vendor/digitaldream/laracrud/src/lara-crud/Crud/Package.php

# php artisan laracrud:mvc users --api
in_array() expects parameter 2 to be array, null given

# php -v
PHP 7.4.4 (cli) (built: Mar 20 2020 13:47:45) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.4, Copyright (c), by Zend Technologies

# composer info | grep laravel/
laravel/framework                     v7.18.0    The Laravel Framework.
laravel/horizon                       v4.3.3     Dashboard and code-driven configuration for Laravel queues.
laravel/passport                      v9.3.0     Laravel Passport provides OAuth2 server support to Laravel.
laravel/tinker                        v2.4.0     Powerful REPL for the Laravel framework.
laravel/ui                            v2.1.0     Laravel UI utilities and presets.

Error during the migration generation

I am getting an error when trying to generate migration from DB.

vendor\digitaldream\laracrud\src\lara-crud\Crud\MigrationCrud.php:222
218| * @throws \Exception
219| */
220| public function generateClassName($table)
221| {

222| $class = 'create' . ucfirst(camel_case($table)) . 'Table';
223|
224| if (class_exists($class)) {
225| throw new \Exception('Migration for table ' . $table . ' already exists');
226| }

Exception trace:

1 LaraCrud\Crud\MigrationCrud::generateClassName("users")
vendor\digitaldream\laracrud\src\lara-crud\Crud\MigrationCrud.php:94

2 LaraCrud\Crud\MigrationCrud::template()
vendor\digitaldream\laracrud\src\lara-crud\Crud\MigrationCrud.php:110

Please use the argument -v to see more details.

Unable to generate controllers

Hello,

I've generated models from the tables using the steps that were outlined. However, when it comes to generating the controller, I'm getting the below error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'where `id` is null' at line 1 (Connection: mysql, SQL: update `users` set  where `id` is null) on line 760 in /vendor/laravel/framework/src/Illuminate/Database/Connection.php

I cannot fathom the source of this issue. Clearly the value between set and where is missing. But, I don't know where or why a query is being executed.

Any help will be appreciated.

Thanks!

Can only be run by console

It is possible that the command can be executed directly in a controller?

Example:

Artisan::call('laracrud:model Test');

When running from a controller:
The command "laracrud:model" does not exist.

MVC create not working

on php artisan laracrud:mvc fields
it product this error.

Class \App\App\Field does not exist

Also view and controller does not working.

Call to undefined functions

Running Laravel 6, PHP Version 7.2 I received the following errors when trying to use Laracrud:

php artisan laracrud:model users

Symfony\Component\Debug\Exception\FatalThrowableError : Call to undefined function LaraCrud\Helpers\str_singular() at C:\laragon\www\goalsetter\vendor\digitaldream\laracrud\src\lara-crud\Helpers\Helper.php:87

php artisan laracrud:controller UserSettings

Symfony\Component\Debug\Exception\FatalThrowableError : Call to undefined function LaraCrud\Crud\camel_case() at C:\laragon\www\goalsetter\vendor\digitaldream\laracrud\src\lara-crud\Crud\Controller.php:185

Add docs to Model

Add additional docs to the header of Model to define relations as property of Model also scopes as a method of Model. So it can be auto suggested while accessing model from Object Context

Multiple relationship to same table, Cannot redeclare App\Models\...

Hello,

When there is a relationship like a table A to table B in field A1, and with table B in field A2, it will result in getB defined twice, the proposed solution is to concatenate the field name: getBA1 and getBA2

I would happy if you give some guide to locate the part of the code responsible to define the method/function names for relationships in order to fork the project, fix and submit a pull request.

Here is the output

php artisan laracrud:mvc usuarios

   Symfony\Component\ErrorHandler\Error\FatalError

  Cannot redeclare App\Models\Usuario::avantelInventarioSimcards()

  at ...\app\Models\Usuario.php:196
    192▕     * avantelInventarioSimcards
    193▕     *
    194▕     * @return \Illuminate\Database\Eloquent\Relations\HasMany
    195▕     */
  ➜ 196▕     public function avantelInventarioSimcards()
    197▕     {
    198▕         return $this->hasMany(AvantelInventarioSimcard::class,'usuario_ult_edicion');
    199▕     }
    200▕

Because there is an uncaught fatal error, the script stopped generating anything else.

Problem with routes generation

Hi, congratulations for the job, I only have one problem the routes are not generated even though the terminal is successful.

API

Create necessary files and class to make RestFul API

Namespace issues

I am getting namespace conflicts on "Model" or "Controller":

php artisan laracrud:model activity_type ActivityType
PHP Fatal error:  Cannot use LaraCrud\Crud\Model as Model because the name is already in use in C:\**********\vendor\digitaldream\laracrud\src\lara-crud\Console\View.php on line 7

In View.php line 7:

  Cannot use LaraCrud\Crud\Model as Model because the name is already in use

I updated Console\View.php to import like:

use LaraCrud\Crud\Model as ModelCrud;

But then I just get this one.

php artisan laracrud:model activity_type ActivityType

PHP Fatal error:  Cannot use LaraCrud\Crud\Controller as Controller because the name is already in use in C:\*********\vendor\digitaldream\laracrud\src\lara-crud\Console\Mvc.php on line 7

In Mvc.php line 7:

  Cannot use LaraCrud\Crud\Controller as Controller because the name is already in use

Have you encountered this before? PHP version 5.6.37 and my composer requires look like this:

"require": {
      "php": ">=5.6.4",
      "laravel/framework": "5.4.*",
      "laravel/tinker": "~1.0",
      "digitaldream/laracrud": "3.*"
    },

Duplicated fileds

There are duplicated files when created a model from DB. The last filed is duplicated.

Vuejs

Create view files compatible with Vuejs

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.