Docker Permission Error in Ubuntu

If you are using Docker in the Ubuntu and receive the permission error as below:

“Got permission denied while trying to connect to the Docker daemon socket at unix …”

The solution just add the current user to the Docker group:

$sudo usermod -a -G docker $USER

Then logout / reboot your machine.

After reboot, try the command below:

$docker run hello-world

If successful, then the result shown as below:

Hello from Docker!
This message shows that your installation appears to be working correctly.

PHP Save array to database in JSON format

If you’re using class, take advantage on using the setter and getter method.

class Example
{
 public function setDisaster($value)
 {
     //convert the array to json format
     $this->potential_disaster = json_encode($value);
 }
 
 public function getDisaster()
 {
     //convert json to array format
     return json_decode($this->potential_disaster);
 }

 public function save()
 {
    $model = new Example();
    $model->save();
 }
}

$obj = new Example();
//Save the array data
$obj->disaster = array(1,2,3);
$obj->save();

//Print the array data
print_r($obj->disaster);


Laravel show the last sql query

Hi, here are the simple steps to show the last sql query in Laravel 5.1:

#enable the query log
DB::enableQueryLog();

#your sql query execution
$query = DB::table('table_name');
$query->where('table_name.project_id', 15);
$res = $query->count();
 
#get your last query 
$query = DB::getQueryLog();
$lastQuery = end($query);

#dump sql
dd($lastQuery);

Credit: http://www.goodbytes.be/article/log-last-executed-eloquent-query-as-plain-sql-in-laravel-5

Laravel: Upload & Download from Storage folder

Hi, here is the basic of upload and download multiple files to storage folder in Laravel.

First, create new upload folder in your Storage –> /storage/uploads

Routes:

#route to upload files
Route::post( 'upload',   ['as' => 'upload',       'uses' => 'UploadController@upload_file']);
#route to download file
Route::get('get-file/{filename}', ['as' => 'getFile', 'uses' => 'UploadController@get_file']);

 

Basic Upload Form:

{!! Form::model( $model, ['route' => ['upload', $model->id], 'method' => 'POST', 'id' => 'form_upload', 'files'=>true] ) !!}
{!! Form::file('files[]', array('multiple'=>true)) !!}
{!! Form::submit('Submit', array('class'=>'send-btn')) !!}
{!! Form::close() !!}


Controller:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Str;

class UploadController extends Controller
{
   /**
   * Upload File
   **/
   public function upload_file() {
     $destination_path = storage_path('uploads');
     $files = $request->file('files');
     foreach($files as $file) {
         $validator = Validator::make(
                      [
                          'file' => $file,
                          'extension' => Str::lower($file->getClientOriginalExtension()),
                      ],
                      [
                          'file' => 'required|max:100000',
                          'extension' => 'required|in:jpg,jpeg,bmp,png,doc,docx,zip,rar,pdf,rtf,xlsx,xls,txt, csv'
                      ]
                     );
 
         if($validator->passes()){
             $filename = $file->getClientOriginalName();
             $upload_success = $file->move($destination_path, $filename);
             if ($upload_success) {
                     #if needed, save to your table
                     $attach = new attachments();
                     $attach->file_name = $filename;
                     $attach->mime = $file->getClientMimeType();
                     $attach->save();
             }
         }
     }
  }

  /**
  * Download file
  **/
  public function get_file($filename)
  {
        $file_path = storage_path('uploads') . "/" . $filename;
        return Response::download($file_path);
  }
}

 

View & Download Attachments:

@foreach($attachments as $attach)
  <tr>
       <td>{!! link_to( route('getFile', $attach->filename) . '/' . $attach->file_name, $attach->file_name) !!} </td>
  </tr>
@endforeach

 

Thats all.. Good Luck.. ok Bye!!!

Laravel: Import & Read Excel file (Use chunk to avoid memory fatal error)

Hi, i’m using Maatwebsite/Larabel-Excel module to upload & read the Excel file in Laravel. This tools also support large Excel file as it is using ‘chunk’ to avoid PHP memory fatal error.

For the installation, please refer to the page.

Here is my Upload Form (resources/view/import.blade.php):

@extends('layouts.master')

@section('content')
            {!! Form::open( ['route' => 'import.excel', 'id' => 'form_import_excel', 'files' => true] ) !!}

Select file to upload:


            {!! Form::file('importExcel'); !!}

            
               {!! Form::submit( 'Upload', ['class' => 'btn btn-primary', 'id' => 'btn-submit-edit'] ) !!}


            {!! Form::close() !!}
         </div><!-- /.box-body -->
      </div><!-- /.col -->
</div><!-- /.row -->
@endsection

 

Route (app/Http/routes.php):

//Import Excel
 Route::get( 'import/excel', ['as' => 'import.excel', 'uses' => 'ImportController@excel']);
 Route::post( 'import/excel', ['as' => 'import.post', 'uses' => 'ImportController@postExcel']);

 

Controller (app/Http/Controllers/ImportController.php):

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Http\Controllers;
use App\User;
use Validator;
use App\Repositories\AuditRepository as Audit;

use Auth;
use Flash;
use Excel;

class ImportController extends Controller
{

 /**
 * @return \Illuminate\Http\RedirectResponse
 */
 public function index()
 {
   //...
 }

 /**
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
 */
 public function excel()
 {
     $page_title = "Import Excel";
     $page_description = "Import & Read the Excel file";

     return view('import', compact('page_title', 'page_description'));
 }
 
 public function postExcel(Request $request)
 {
     ini_set('memory_limit',-1);
 
     $destination_path = storage_path('uploads');
     $_arr_excel_ext = array('xls', 'xlsx');
 
     if (!$request->file('importExcel')->isValid()) {
        Flash::error("Sorry, there is no file attached on the form!");
        return redirect()->route('import.excel');
     }
 
     $file = $request->file('importExcel');
 
     if (!in_array($file->getClientOriginalExtension(), $_arr_excel_ext)) {
        Flash::error("Sorry, please use .xls or .xlsx extension!");
        return redirect()->route('import.excel');
     }
 
     if (!$file->move($destination_path, $file->getClientOriginalName())) {
        Flash::error("Sorry, error on loading excel!");
        return redirect()->route('import.excel');
     }

     //use 'chunk' to read large excel data file
     Excel::filter('chunk')->load($file)->chunk(250, function($results)
     {
          foreach($results as $row)
          {
                //save in database or do whatever you like here
                //print_r($row)
                echo "<br>" . $row['column_name_in_lowercase'];
 
          }
     });
 }
 
}

Good Luck.. ok Bye 😉

Install Laravel on Ubuntu 14.04

Make sure you have Composer installed on your Ubuntu

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

 

Download the Laravel

composer global require "laravel/installer"

 

Place the Laravel execution dir ~/.composer/vendor/bin in your PATH

gedit /etc/environment

#Then run the command below for the changes
. /etc/environment

 

Then create your new project with Laravel

laravel new myfirstapp

 

*To check which Laravel version you’re using

php artisan -V

Python: Read Excel file with xldr

First make sure you’ve install the xlrd module:

$ sudo pip install xlrd

Then here are the basic code to read the Excel file with Python:

#!/usr/bin/python

import xlrd

def read_file_xlsx(read_file):
    workbook = xlrd.open_workbook(read_file)
    worksheet = workbook.sheet_by_index(int(worksheet_index))
    num_cols = worksheet.ncols # Number of columns
    for row_n in range(0, worksheet.nrows): # Iterate through rows
        print ('Row: %s' % row_n) # Print row number
       for col_n in range(0, num_cols): # Iterate through columns
            cell_value = worksheet.cell(row_n, col_n) # Get cell object by row, col
           print ('Column: [%s] cell_obj: [%s]' % (col_n, cell_value))

    return 'anything'

results = read_file_xlsx('my_file.xlsx');