Tuesday, October 18, 2016

How to pass parameter from one page to another in Laravel? | How to hide parameter from URL/ Route in Laravel?

laravel parameter passing


In this session I'm gonna write about how you can pass parameter from one page to another and while passing the value how you can hide it. Let's start the discussion...


1.  Suppose I want to send a parameter through a button from the first page to another page. Here, suppose course_id .

 <li> <a  href="{{route('registration',['course_id' => Crypt::encrypt('1') ])}}">IELTS</a> </li>
2. Now We're going to encrypt the parameter first and send it to through the route 'registration' .

3. Let's write the route :

Route::get('/registration/{course_id}',[
   'uses'=>'AppController@getregistration',
    'as'=>'registration'
]);

4. Controller Part :

public function getregistration($course_id)
    {
        $course_id = Crypt::decrypt($course_id);    
        return view('index')->with('course_id',$course_id);
    }

So when we send the variable course_id from the first page to second page, you'll see the course_id as encrypted in route.

5. Now if we want to save the course_id in database inside of  our second page. You can do like that:

 <input type="hidden" name="course_id" value="{{ $course_id }}" class="form-control" >
So this is how you can send a parameter from one page to another and save into database in second page.










Laravel Event | How to send Email using Laravel Event?

laravel event listener


1. First Configure your Email Setting in you project. Do the necessary changes on .env file.
2. Run the following command first inside of your project using cmd.

php artisan make:event SendMail
3. This will generate a SendMail.php file inside App\Events directory. The file would be like this after writing the necessary codes :
<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class SendMail
{
    use InteractsWithSockets, SerializesModels;
    public $id;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($id)
    {
        $this->id = $id;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

4. Now run the following command for crating a listener for the event.

php artisan make:listener SendMailFire --event="SendMail"
5. This will generate a SendMailFire.php file inside App\Listeners directory. The file would be like this after writing the necessary codes :
<?php

namespace App\Listeners;

use App\Events\SendMail;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\User;
use Mail;

class SendMailFired
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  SendMail  $event
     * @return void
     */
    public function handle(SendMail $event)
    {
          $user = User::find($event->id)->toArray();
            
          Mail::send('send', $user, function($message) use ($user) {
            $message->to($user['email']);
            $message->subject('Event Testing');
        });
    }
}
6. In above code, you are seeing a 'send' inside of your mail function. This actually a blade page which user will see. For demo purpose I'm sending the below message (send.blade.php):

<html>
    <head>
       <title>EVENT TEST MAIL</title>     
    </head>
    <body>
        <h3> Hello Event Testing ..</h3>
    </body>
</html>

7. Now Let's create a controller. So the request will be called. And event will be fired. Let's store some user data with name, email, password etc. So when a User's data saved into database the Event been fired and the User will get mail.

(UserController.php)
 public function postRegistration(Request $request)
    {
        $user = new User();         
        $user->name = $request->Input(['name']);
        $user->email=$request->Input(['email']);
        $user->password=$request->Input(['password'])       
        $user->save();        
        Event::fire(new SendMail($user->id));               
     return Response::json($user);
    }


















How to Upload Laravel Project on Subdomain?

laravel project on subdomain




If you need to upload a Laravel Project on a Subdomain of Live Server. Here is the short tutorial on it. If you have already created a subdomain. Then you can just upload the files and route the server to public_html where you upload the files. If you don't have the subdomain, then you have to create the subdomain. Don't get tensed.I'm gonna elaborate it very easily. Let's the start the session.

1. First You have logged in your cpanel account Like : 192.185.94.163/cpanel.

2. Then If you have Database ..You need to create a User first and then database as well. If you don't have you can skip it.

3. You can create the database by clicking MySQL Databases on DATABASES section.

4. Crate a new user in MySQL Users Section like following picture.
mysql users

5. Then Crate a new database Create New Database like following picture.

mysql

6. Now we need to add the user to database in Add User To Database like following picture.

mysql adding database to user


7. Now we need to change the configuration of our Laravel project in .env file of Database Section.

7. Then we need to upload the laravel project inside of public_html as format .zip. After uploading we need to unzip the file.

file manager


8. Suppose we have uploaded the registration project inside of public_html. so our project directory should be like this.

public_html


9. Now we need to create a sub domain. You can find it on DOMAINS section.

10. Give a sub domain a name . Select the main domain from dropdown. Assign Document Root to public_html/registration/public. As we already know our main project is inside of registration directory. Press the create button. And that's it. our subdomain with project has crated.

subdomain


11. Now if you access the url (with subdomain). You will see your laravel project on Live.

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.















Sunday, August 28, 2016

How to check php version on xampp? | How to know what version of PHP is used on my xampp?


PHP version on xampp


XAMPP is a popular web server for running PHP script. Sometimes we need to know which version of PHP we used in XAMPP. So in this tutorial I am gonna show how you can check PHP version on XAMPP.



1. Go to your htdocs folder on XAMPP.

2. Create a txt file,  write down the following code in it and save  it as phpinfo.php .

<?php
   phpinfo();
?>
3. Now run the server and access the file from url ( like: localhost/phpinfo.php )

4. You'll see the version of PHP in the webpage. 












Saturday, August 27, 2016

How to make Laravel Authentication | Laravel 5 Authentication | How to Make User Login and Registration Laravel 5

laravel authentication



In laravel you can use Laravel Authentication  for authenticate user. By a single command you gen generate full authentication system with resources and routes. Let's see how you can do it ..

Go to your project directory -->> open cmd and run the following command:

php artisan make:auth
you'll see the list of views, route and controller generated in your command prompt.

cmd



Now if you access the project in url ..you'll see the login and register page like this:

Register Page:

sign up page


Login Page:

sign in page


So this is the process how you can make simple Authentication system using Laravel Authentication. 


Tuesday, August 23, 2016

How to import csv/ excel file into database in laravel? | Upload CSV / Excel file and import it to database using Laravel



laravel import csv



In this tutorial I have shown you how you can Import  CSV/ excel file into Database Sometimes we need to import csv / excel file into database for update purpose or new data has came which we need to save in database . 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. Now go to route and write the following code in routes.php

<?php

Route::get('importExport', 'ImportController@importExport');
Route::post('importExcel', 'ImportController@importExcel');


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

9.  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 importExcel()
    {
    // Get current data from items table
            $titles = Item::lists('title')->toArray();

            if(Input::hasFile('import_file')){
                $path = Input::file('import_file')->getRealPath();
                $data = Excel::load($path, function($reader) {
                })->get();

                if(!empty($data) && $data->count()){
                    $insert = array();

                    foreach ($data as $key => $value) {
                        // Skip title previously added using in_array
                        if (in_array($value->title, $titles))
                            continue;

                        $insert[] = ['title' => $value->title, 'description' => $value->description];

                        // Add new title to array
                        $titles[] = $value->title;
                    }

                    if(!empty($insert)){
                        DB::table('items')->insert($insert);
                    }
                }
            }
            return back();    
    }
}
* The above code will help you to resist from uploading redundant data.

10. 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>Import  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="#"> Import Excel or CSV into  Database</a>
   </div>
  </div>
 </nav>
 <div class="container">
  <form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data" >
   <input type="file" name="import_file" />
     {!! Form::token(); !!}
                 {!!   csrf_field() ; !!} 
   <button class="btn btn-primary">Import File</button>
  </form>
 </div>
</body>
</html>


11. Now if you access the route you'll see the view page and by clicking on 'choose file' button you can choose the file and by clicking on 'import file' you can import the file into database successfully.


file upload





12. Here is a demo of Excel file which you can upload:
demo



I hope you like the tutorial. By this tutorial you can import the csv or excel file easily into database.


Wednesday, July 27, 2016

How to install Jekyll on Windows? | How to make a Website using Jekyll?


jekyll



Jekyll is a popular platform to transform your plain text into static Website or Blog. It's very easy to install on windows. Let's see how  you can install it with just 3 commands.


1. Open the command prompt ( cmd ) with administrative mood access.
2. Run the following command:

@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin

3. Close the command prompt and open a new cmd with administrative  access.
4. Now Run the following command:

choco install ruby -y

5. Now again  close the command prompt and open a new cmd with administrative  access.
6. Now Run the following command:

gem install jekyll
7. Close the command prompt.

Jekyll has successfully installed. Now let's make a demo website :

1. Open cmd in the directory where you want to keep the blog file. Run the following command one after another finished :

jekyll new testblog

cd testblog

jekyll serve

So our jekyll server has started. Now in browser write the following url and You'll your test website:

http://localhost:4000/

You'll see your test Website like following :

jekyll demo





So that's it for today. Hope you like the short tutorial on Jekyll.




































Tuesday, July 26, 2016

Laravel 5 database backup | How to backup your database using Laravel Backup package?

Laravel Database backup



It's a good habit if you maintain a backup database of your project. So that every update of your database will be kept track. Or otherwise some deleted some data by mistake you can keep track of that too.

Before we start make sure you have mysqldump installed in your system. By default it already came with the XAMPP/ LAMP/ WAMP etc. But we need to add the following line in config/database.php in mysql array (for laravel only):

'dump_command_path' =>'C:\xampp\mysql\bin',
Now Let's start How you can backup your database in Laravel

1. First you need to install a package in your application.

composer require spatie/laravel-backup
2. Add the following line in providers Array of config/app.php file.
Spatie\Backup\BackupServiceProvider::class,
3.Then run the following command:
php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"
4. Now if you run the following command it will automatically create a backup database with date in storage/app folder in zip format.


 php artisan backup:run

















Friday, July 15, 2016

Laravel Autocomplete Search with Bootstrap Typeahead JS

autocomplete search




Autocomplete search is required when we work with large database search items. Because it's not user friendly to use dropdown for every item. So when we have to large data searching we use Autocomplete Search. Here I've used popular autocomplete search using Bootstrap Typehead JS.




1. Make a Model and a Table named "Item" with the following command.

php artisan make:model Item  -m 

2. Change the Model Item.php with the following code:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
      public $fillable = ['title','description'];
}

3. Change the items migration file ( you can get it in database/migrations directory with the following 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");
    }
}


4. Now run the following command:

php artisan migrate

5. Put some demo data in database with the name and description in items table.

6. Now we have to create the route:

routes.php

<?php

Route::get('/search',[
 'uses' => 'SearchController@search',
 'as'=>'search'
 ]);

Route::get('/autocomplete',[
 'uses'=>'SearchController@autocomplete',
 'as'=>'autocomplete'
 ]);
7. Make SearchController.php with the following command:

php artisan make:controller SearchController

8.  Change the SearchController.php code with the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Item;

class SearchController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function search()
    {
        return view('search');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function autocomplete(Request $request)
    {
        $data = Item::select("title as name")->where("title","LIKE","%{$request->input('query')}%")->get();
        return response()->json($data);
    }
}
9. Now we have to make search.blade.php:
<html>
 <head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>  
 </head>
 <body>

 <div class="container">
     <h1> Laravel Autocomplete Search using Bootstrap Typeahead JS</h1>   
     <input class="typeahead form-control"  type="text">
 </div>

<script type="text/javascript">
    var path = "{{ route('autocomplete') }}";
    $('input.typeahead').typeahead({
        source:  function (query, process) {
        return $.get(path, { query: query }, function (data) {
                return process(data);
            });
        }
    });
</script>
 </body>
</html>

10. That's it, now when you search the route and write a name of keyword in searchBox you might have seen the relevant search name like the following:






typehead bootstrap demo