Laravel 5 Global CRUD Class

Before anyone asks, I looked at the generators CRUDand I know everything about resource routes Laravel, but that’s not quite what I am pulling for this.

I want to create one route with pair parameters and one global class that (uses / extends?) The model controller for simple operations CRUD. We have about 20 models and creating a resource Controllerfor each table would be more time-consuming than finding a way to create a global class CRUDto handle all calls like " api" and any request ajax json, for example, the create / update / destroy instruction.

So my question is, what is the cleanest and best way to structure a class to handle all the requests CRUDfor each Modelthat we have, without having to have a resource Controllerfor each Model? I tried to investigate this and cannot find any links, except for one, for generators CRUDand links describing laravel Resource route.

+4
source share
3 answers

The easiest way is to do the following:

  • Add a route for your resource controller:

    Route::resource('crud', 'CrudController', array('except' => array('create', 'edit')));
    
  • Build your crud controller

    <?php namespace App\Http\Controllers;
    
    use Illuminate\Routing\Controller;
    use App\Models\User;
    use App\Models\Product;
    use Input;
    
    class CrudController extends Controller
    {
        const MODEL_KEY = 'model';
    
        protected $modelsMapping = [
            'user' => User::class,
            'product' => Product::class
        ];
    
        protected function getModel() {
            $modelKey = Input::get(static::MODEL_KEY);
            if (array_key_exists($modelKey, $this->modelsMapping)) {
                return $this->modelsMapping[$modelKey];
            }
    
            throw new \InvalidArgumentException('Invalid model');
        }
    
        public function index()
        {
            $model = $this->getModel();
            return $model::all();
        }
    
        public function store()
        {
            $model = $this->getModel();
            return $model::create(array_except(Input::all(), static::MODEL_KEY));
        }
    
        public function show($id)
        {
            $model = $this->getModel();
            return $model::findOrFail($id);
        }
    
        public function update($id)
        {
            $model = $this->getModel();
            $object = $model::findOrFail($id);
            return $object->update(array_except(Input::all(), static::MODEL_KEY));
        }
    
        public function destroy($id)
        {
            $model = $this->getModel();
            return $model::remove($id);
        }
    }
    
  • :) model, - . . id = 5 do

    GET /crud/5?model=user
    

, , , , .

, , - , - - . .

+3

CRUD, datagrid, phpGrid.

: http://phpgrid.com/example/phpgrid-laravel-5-twitter-bootstrap-3-integration/ , . - .

CRUD:

// in a controller
public function index()
{
    $dg = new \C_DataGrid("SELECT * FROM orders", "orderNumber", "orders");
    $dg->enable_edit("FORM", "CRUD");
    $dg->display(false);

    $grid = $dg -> get_display(true); 

    return view('dashboard', ['grid' => $grid]);
}
+3

CRUD, , , , . , , URI CRUD. , :

example.com/user/{id?} // get all or one by id (if id is available in the URI)
example.com/user/create // Show an empty form
example.com/user/edit/10 // Show a form populated with User model
example.com/user/save // Create a new User
example.com/user/save/10 // Update an existing User
example.com/user/delete/10 // Delete an existing User

user - , , , example.com/product/create , , , :

Route::get('/{model}/{id?}', 'CrudController@read');
Route::get('/{model}/create', 'CrudController@create');
Route::get('/{model}/edit/{id}', 'CrudController@edit');
Route::post('/{model}/save/{id?}', 'CrudController@save');
Route::post('/{model}/delete/{id}', 'CrudController@delete');

app\Providers\RouteServiceProvider.php boot :

public function boot(Router $router)
{
    $model = null;

    $router->bind('model', function($modelName) use (&$model, &$router)
    {
        $model = app('\App\User\\'.ucfirst($modelName));

        if($model)
        {
            if($id = $router->input('id'))
            {
                $model = $model->find($id);
            }

            return $model ?: abort(404);
        }
    });

    parent::boot($router);
}

CrudController, :

class CrudController extends Controller
{
    protected $request = null;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function read($model)
    {
        return $model->exists ? $model : $model->all();
    }

    // Show either an empty form or a form
    // populated with the given model atts
    public function createOrEdit($model)
    {
        $classNameArray = explode('\\', get_class($model));

        $className = strtolower(array_pop($classNameArray));

        $view = view($className . '.form');

        $view->formAction = "$className/save";

        if(is_object($model) && $model->exists)
        {
            $view->model = $model;

            $view->formAction .= "/{$model->id}";
        }

        return $view;
    }

    public function save($model)
    {
        // Validation required so do it
        // Make sure each Model has $fillable specified
        return $this->model->fill($this->request)->save();
    }

    public function delete($model)
    {
        return $this->model->delete();
    }
}

, - , :

<form action="{{url($formAction)}}" method="POST">

    <input
    type="text"
    class="form-control"
    name="first_name" value="{{old('first_name', @$model->first_name)}}"
    />
    <input type="Submit" value="Submit" />
    {!!csrf_field()!!}

 </form>

, , , / , views/user/form.blade.php views/product/form.blade.php ..

, , . , , , .

0

All Articles