Laravel show the last sql query

Posted: September 28, 2016 in Laravel, Uncategorized
Tags: ,

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

#enable the query log

#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


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


#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() !!}


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'
             $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();

  * 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)
       <td>{!! link_to( route('getFile', $attach->filename) . '/' . $attach->file_name, $attach->file_name) !!} </td>


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

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):


            {!! 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 -->


Route (app/Http/routes.php):

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


Controller (app/Http/Controllers/ImportController.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)
     $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
                echo "<br>" . $row['column_name_in_lowercase'];

Good Luck.. ok Bye😉

Install Laravel on Ubuntu 14.04

Posted: June 26, 2016 in Laravel, Php
Tags: ,

Make sure you have Composer installed on your Ubuntu

curl -sS | 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

Posted: June 20, 2016 in Python

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:


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');

Hi, here i would like to share the way to search string with pattern in Mysql. I’m using the Mysql Regexp function.

Example i want to find numbers that match the X pattern in below format:

Format string to search in array:


$format_array = array("12X.LM.XX.XXXX", "123.45.XXXX", "72.67X.XXXX");

foreach ($format_array as $format) {
 $arrExp = explode('.', $format);
 if (preg_match_all("/X+/", $format, $output_array)) {
     foreach ($output_array[0] as $key=>$val) {
         $count = strlen($val);
         foreach ($arrExp as $key=>$s) {
             if (substr_count($s, 'X') == $count) {
                  $arrExp[$key] = str_replace($val, '[a-z0-9.]{'.$count.'}', $s);
     $str_format = implode('.', $arrExp) . "$";
     #example output pattern $str_format = 72.67[a-z0-9.]{1}.[a-z0-9.]{4}$
     #here is your sql command with the pattern
     $sql = "SELECT * FROM table_name WHERE col REGEXP '$str_format";



Here is my step to perform background process with Python using PHP command:

Server: Linux Ubuntu 14.04,
PHP 5.5
Python 2.7.6

# Make sure your python script is executeable
chmod +x /path/to/

function run_command(array $input)
 $arg1 = $input['arg1'];
 $arg2 = $input['arg2'];
 $command = "python $arg1 $arg2";
 #change to my python project directory
 #enable debugging with 2>&1
 #throw output in $output

 exec("cd /home/python_project/app && $command 2>&1", $output);

Ok Good Luck!