Laravel installation

This is a full tutorial of a suggested way to install Grocery CRUD Enterprise to your already existing project with Laravel version 5.6.

Notice: Grocery CRUD Enterprise is a framework agnostic library. That simply means that it doesn’t matter which framework you are using and it doesn’t matter which architecture you are using. It can work in any PHP platform! This tutorial is taking some architecture decisions basically for you! If you need to have the full freedom of what structure to choose we are suggesting to see the full installation guide here.

Step 1. Copying the zip file to the correct folder 

From the email that you’ve received or from the user’s page (you will get instructions at the email of how to access user’s page) download the zip file that say’s “With composer”.

Your file will look something like this: grocery-crud-enterprise-v2.3.7.zip. Now at your root directory create a new directory with name artifacts and copy the zip file there without unziping it. The final file structure will look something like this:

├── app
├── artifacts
│   └── grocery-crud-enterprise-v2.5.7.zip
├── artisan
├── bootstrap
├── composer.json
├── composer.lock
├── config
├── database
├──.env
├──.gitattributes
├──.gitignore
├── package.json
├── phpunit.xml
├── public
├── readme.md
├── resources
├── routes
├── server.php
├── storage
├── tests
├── vendor
└── webpack.mix.js

Step 2. Update composer.json

Now we will need to update the composer.json file and add the extra grocery CRUD Enterprise files. More specifically you will need to add those lines (marked as bold):


    "type": "project",
"repositories": [
        {
            "type": "artifact",
            "url": "artifacts/"
        }
    ],
    "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.6.*",
        "laravel/tinker": "^1.0",
"grocerycrud/enterprise": "2.*.*"
    },

So your composer.json will look something like this:

Step 3. Update composer from the console

Update composer in order to get the library of Grocery CRUD Enterprise at the vendor folder
Now go to your root folder with your terminal and simply type:

composer update

You will be able to see many updates such us zend db but you will also see this:

 - Installing grocerycrud/enterprise (2.5.7)

Now Grocery CRUD Enterprise is available through composer so you could see the below folder structure at your vendor folder:

vendor
├── ...
...
├── fzaninotto
├── grocerycrud
│   └── enterprise
│       ├── change-log.txt
│       ├── composer.json
│       ├── examples
│       ├── LICENCE.md
│       ├── public
│       └── src
├── hamcrest
...

Step 4. Copying the assets folder to our project

Now that we have available the package through vendor, we will also need to copy the public folders to our project. More specifically, navigate to: vendor/grocerycrud/enterprise/public and you will see the folder with name grocery-crud. Now go to your public folder and create a new folder with name assets. Then copy the folder grocery-crud to the assets folder. The final folder structure will look something like this:

├── app
├── artifacts
├── artisan
├── bootstrap
├── composer.json
├── composer.lock
├── config
├── database
├── package.json
├── phpunit.xml
├── public
    ├── assets
    │   └── grocery-crud
    │       ├── css
    │       ├── fonts
    │       ├── images
    │       ├── index.html
    │       └── js
    ├── css
    │   └── app.css
    ├── favicon.ico
    ├── index.php
    ├── js
    │   └── app.js
    ├── robots.txt
    └── web.config
├── readme.md
├── resources
├── routes
├── server.php
├── storage
├── tests
├── vendor
└── webpack.mix.js

Step 5. Create the configuration file for Grocery CRUD Enterprise
Go to your project’s config folder and create a file with name grocerycrud.php that will include the below code:

Important Notice: Make sure that you have configured the correct website path at the file .env. More specifically change the below code:

APP_URL=http://localhost

to your original project path. For example:

APP_URL=http://local.grocerycrud.com

Step 6. Configuring our routes and creating our controller to render our CRUD
Now we will need to create our routes to point to our controller. Let’s start by configuring routes! Go to routes/web.php and add those two lines of code:

// web.php
Route::get('customers', 'CustomersController@datagrid');
Route::post('customers', 'CustomersController@datagrid');

As you can see at the above code, we are simply saying that if you have at the first parameter the word customers then direct the user to CustomersController and the function datagrid. Now a common mistake that we are often seeing is that developers are forgetting to also allow post requests to be available. Grocery CRUD Enterprise is using GET and POST requests in order to work.

Now that we’ve created our routes let’s create our empty for now Controller. In order to do that go to: app/Http/Controllers/ and create a new file with name CustomersController.php. There add a simple controller like the one below:

As you can also see from the above code, we did also add the use GroceryCrud\Core\GroceryCrud; in order to make sure that Grocery CRUD Enterprise can load. In case this line doesn’t work for you, please make sure that you follow the above steps in order to install Grocery CRUD Enterprise with composer first.

Now our datagrid has just a response “Hello World!” So if you go to your website and navigate to: example.com/customers you should see the phrase “Hello World!”. If you see this message that means that your routes are configured correctly and that we can load Grocery CRUD Enterprise

Step 7. Preparing our blade view for a generic template to load our output string, JS and CSS files

In Grocery CRUD Enterprise we are using the function render() to render 3 main things:

  • The HTML output string
  • The CSS files
  • The JavaScript files

So it is important to have a template that can load all of the above. Usually in our project we’ve already have a template to load the CSS and JS files but in case we don’t, we can create a new template view like the below. Go to: resources/views/ and create a new file with name: default_template.blade.php. Then copy the below code:

As you may also notice (and this is the second most common mistake for Laravel installations) we are also adding the CSRF token as a meta tag on the header:

<meta name="csrf-token" content="{{ csrf_token() }}">

And we are are having the CSRF token as a default header with the below code:

$(document).ready(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
});

As this will be a generic template we are also making sure that we are checking if jQuery exists with the below code:

if (typeof $ !== 'undefined') {

Step 9. Load Grocery CRUD Enterprise and make it work!

Now finally after 9 steps it is time to see Grocery CRUD Enterprise working on your screen! In order to do that your final controller will look like below:

Let’s explain a little bit what we did at the controller. Grocery CRUD Enterprise needs two kind of configurations:

  • The database connection
  • The Grocery CRUD Enterprise configurations

The database configuration can be taken dynamically from Laravel as it is already located at: config/database.php. So in order to retrieve the database connection data we are simply doing this:

$databaseConnection = config('database.default');
$databaseConfig = config('database.connections.' . $databaseConnection);

In our case, our default database is MySQL and that’s why we have as hardcoded the value of the Zend driver as Pdo_Mysql So the final result of the configuration is:

private function _getDatabaseConnection() {
        $databaseConnection = config('database.default');
        $databaseConfig = config('database.connections.' . $databaseConnection);
        return [
            'adapter' => [
                'driver' => 'Pdo_Mysql',
                'database' => $databaseConfig['database'],
                'username' => $databaseConfig['username'],
                'password' => $databaseConfig['password'],
                'charset' => 'utf8'
            ]
        ];
}

Please have in mind that for different databases you will need to change the adapter driver. For example you can use the following drivers:

And you can also see all the available database connections from Zend Db adapter.

The next configuration is the configuration that we did describe at step 5 and we are simply calling this configuration like this:

$config = config('grocerycrud');

Now let’s explain quickly what the below code is doing:

if ($output->isJSONResponse) {
    return response($output->output, 200)
          ->header('Content-Type', 'application/json')
          ->header('charset', 'utf-8');
}

At the above code, we are checking if the response is JSON and if not we are calling our main template view. In case the response is JSON then we are simply returning the JSON response that it is already formatted as a string by Grocery CRUD Enterprise with some JSON headers.

Step 10. [IMPORTANT] Some advices about the best way to structure your controller

With Grocery CRUD Enterprise, we’ve notice that we are repeating the same code again and again. That’s why it is strongly recommended to move the initial call with the configurations and the final output code into two separate functions. For example the above controller can be refactored with the below one:

So as you can also see our current implementation of customers is only the below lines:

public function datagrid()
{
    $crud = $this->_getGroceryCrudEnterprise();

    $crud->setTable('customers');
    $crud->setSubject('Customer', 'Customers');

    $output = $crud->render();

    return $this->_show_output($output);
}

And of course we can only now copy those few lines of code in case we need to create another CRUD.

For example:

public function offices()
{
    $crud = $this->_getGroceryCrudEnterprise();

    $crud->setTable('offices');
    $crud->setSubject('Office', 'Offices');

    $output = $crud->render();

    return $this->_show_output($output);
}

Step 11. Enjoy ❤️

Don’t forget to celebrate your installation. Take a break and drink some coffee ☕ , tea or water and enjoy the power of Grocery CRUD Enterprise at your project!

In case you have issues with the installation also consider to check the most common mistakes of Grocery CRUD here: https://youtu.be/X0gnDD0qTS8. This video has examples for Codeigniter framework but you can follow the same instructions for Laravel framework as well.