Monday, September 5, 2016

How to upload file into Dropbox in Laravel | Working with Dropbox API to upload file | Laravel 5 dropbox api file upload

laravel file upload dropbox





Dropbox a popular file hosting provider provides cloud storage till 2GB for free user. In this tutorial we'll use dropbox api to upload file into dropbox. By using dropbox we can keep backup of out project files, database and so on. So let's start how we can do it ..


1. First we need to install thephpleague/flysystem-dropbox package in our project.
2. Then we need to create a dropbox app and after creating we need to get the App's secret key and token.
3. Let's put this in .env file as following:

DROPBOX_TOKEN=app_token
DROPBOX_SECRET=app_secret

4. Now go to vendor\dropbox\dropbox-sdk\lib\dropbox\RequestUtil.php in your project directory and comment out the following lines :

/*
if (strlen((string) PHP_INT_MAX) < 19) {
    // Looks like we're running on a 32-bit build of PHP.  This could cause problems because some of the numbers
    // we use (file sizes, quota, etc) can be larger than 32-bit ints can handle.
    throw new \Exception("The Dropbox SDK uses 64-bit integers, but it looks like we're running on a version of PHP that doesn't support 64-bit integers (PHP_INT_MAX=" . ((string) PHP_INT_MAX) . ").  Library: \"" . __FILE__ . "\"");
}*/

otherwise later when you run the project you'll get following error:

The Dropbox SDK uses 64-bit integers, but it looks like we're running on a version of PHP that doesn't support 64-bit integers 


5. Now let's create the routes in routes.php
Route::get('dropboxUpload', 'dropController@dropboxUpload');
Route::post('dropboxFileUpload', 'dropController@dropboxFileUpload');

6. Now we gonna make the dropController.php with the following command:

php artisan make:controller dropController 
7. Change the following code with the existing code in dropController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Input;
use Validator;
use Illuminate\Support\Facades\Redirect;
use League\Flysystem\Dropbox\DropboxAdapter;
use League\Flysystem\Filesystem;
use Dropbox\Client;
use Dropbox\WriteMode;

class dropController extends Controller
{
    public function dropboxUpload()
 {
  return view('droboxUpload');
 }
 
    public function dropboxFileUpload()
        {       
         $Client = new Client(env('DROPBOX_TOKEN'), env('DROPBOX_SECRET'));
         $file = fopen(Input::file('image'), 'rb');
         $size = filesize(Input::file('image'));
         $dropboxFileName = '/'.Input::file('image')->getClientOriginalName();
         $Client->uploadFile($dropboxFileName,WriteMode::add(),$file, $size);
         $links['share'] = $Client->createShareableLink($dropboxFileName);
         $links['view'] = $Client->createTemporaryDirectLink($dropboxFileName);
         print_r($links); 
        } 
}

8. Now we gonna create the dropboxUpload.blade.php :

<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Dropbox with Laravel 5</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
</head>
<body>
 <nav class="navbar navbar-default">
  <div class="container-fluid">
   <div class="navbar-header">
    <a class="navbar-brand" href="#">Upload File to Dropbox using Laravel </a>
   </div>
  </div>
 </nav>
 <div class="container">
  <form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ URL::to('dropboxFileUpload') }}" class="form-horizontal" method="post" enctype="multipart/form-data" >
   <input type="file" name="image" />
     {!! Form::token(); !!}
       {!!   csrf_field() ; !!} 
   <button class="btn btn-primary">Import File</button>
  </form>

 </div>
</body>
</html>
That's it. When you visit the route you'll see the upload option in view. You upload the file and it'll automatically upload into Dropbox.

Hope this tutorial will help you to upload file into DropBox.














Sunday, September 4, 2016

How to Export CSV/xls/xlsx from Model in Laravel | How to Download Table Data / Database to CSV /xls / xlsx in Laravel?

laravel export csv


In this tutorial I have shown you how you can download/ Export database to CSV/ xls/ xlsx. Sometimes we need to download the database as csv or excel format for seeing the report of the project. Here we used Maatwebsite/Laravel-Excel package for generating the csv or excel format.
So lets see how we can do it..


1. First we need to install the Maatwebsite/Laravel-Excel package in our laravel project. Installing process has fully described in documentation itself. Bu if you find any difficulty you can comment it here.

3. Let's create a Model  and database with  name 'Item' with the following command in cmd inside of your project :

php artisan make:model Item  -m  
4. Use following code in Model name Item.php :
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
     public $fillable = ['title','description'];
}
5. Now go to migration file and change the following code with the existing code:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('items');
    }
}
6. Now run the following command in cmd inside of your project. This command will generate the database with title and description in items table which is in phpmyadmin.
php artisan migrate

7. Let's put some demo data on your database table in phpmyadmin.


phpmyadmin


8. Now go to route and write the following code in routes.php

<?php

Route::get('importExport', 'ImportController@importExport');
Route::get('downloadExcel/{type}', 'ImportController@downloadExcel');


9. Now let's create Importcontroller.php using following code:
php artisan make:controller ImportController  

10.  Now change the following  code with the existing code of Importcontroller.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
use Excel;
use App\Item;
use Illuminate\Support\Facades\Input;
use Validator;
use Illuminate\Support\Facades\Redirect;

class ImportController extends Controller
{
    public function importExport()
 {
  return view('importExport');
 }
 public function downloadExcel($type)
 {
  
         if($type == 'csv'){
                $data = Item::get()->toArray();
                return Excel::create('demo_example', function($excel) use ($data) {
                    $excel->sheet('mySheet', function($sheet) use ($data)
                         {
                                $sheet->fromArray($data);
                             header('Content-Encoding: UTF-8');
                                header('Content-type: text/csv; charset=UTF-8');
                            header('Content-Disposition: attachment; filename=itsolutionstuff_example.csv');
                            echo "\xEF\xBB\xBF";
                        });
                        })->download($type);
             }

        else {
                    $data = Item::get()->toArray();
                    return Excel::create('itsolutionstuff_example', function($excel) use ($data) {
                     $excel->sheet('mySheet', function($sheet) use ($data)
                      {
                           $sheet->fromArray($data);
                        });
                     })->download($type);
        }
   
    }
}
* The above code is UTF-8 support. So anytime language is suitable for the above code.

11. Now let's create the view page and name it as importExpor.blade.php and use the following code:
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Export Laravel </title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
</head>
<body>
 <nav class="navbar navbar-default">
  <div class="container-fluid">
   <div class="navbar-header">
    <a class="navbar-brand" href="#"> Export in Excel and CSV in Laravel </a>
   </div>
  </div>
 </nav>
 <div class="container">
  <a href="{{ URL::to('downloadExcel/xls') }}"><button class="btn btn-success">Download Excel xls</button></a>
  <a href="{{ URL::to('downloadExcel/xlsx') }}"><button class="btn btn-success">Download Excel xlsx</button></a>
  <a href="{{ URL::to('downloadExcel/csv') }}"><button class="btn btn-success">Download CSV</button></a> 
 </div>
</body>
</html>


12. Now if you access the route you'll see the view page and by clicking on any button you can download the required data from the table.


demo


I hope this tutorial will help you to download the excel or csv from database.