Wednesday, September 23, 2015

Use Web Socket for Chat in Laravel 5 (Using Ratchet for particular user )

Use Web Socket for Chat in Laravel 5 step by step:

If you want to create a chat server for particular user in Laravel 5, then this blog will help you. Its a very easy and fast way to use web socket.

For this firstly you have to install Ratchet package in your application.

Step1:
For this open your composer.json and write this code in "require" key:

"cboden/ratchet": "0.3.*"

Now open open your terminal and go to your root path and run this command

composer update

It will install this package in your application.

Use Web Socket for Chat in Laravel 5


Step2:

Now create a controller and write functions on it , also include the package files.
For this , just go to your terminal and write this command:

php artisan make:controller ChatController


Now go to this file and write the following code on it:

<?php
namespace App\Http\Controllers;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class ChatController implements MessageComponentInterface
{
    protected $clients;
    private $subscriptions;
    private $users;

    public function __construct()
    {
        $this->clients = new \SplObjectStorage;
        $this->subscriptions = [];
        $this->users = [];
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        $this->users[$conn->resourceId] = $conn;
    }

    public function onMessage(ConnectionInterface $conn, $msg)
    {
        $data = json_decode($msg);
        switch ($data->command) {
            case "subscribe":
                $this->subscriptions[$conn->resourceId] = $data->channel;
                break;
            case "message":
                if (isset($this->subscriptions[$conn->resourceId])) {
                    $target = $this->subscriptions[$conn->resourceId];
                    foreach ($this->subscriptions as $id=>$channel) {
                        if ($channel == $target && $id != $conn->resourceId) {
                            $this->users[$id]->send($data->message);
                        }
                    }
                }
        }
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        unset($this->users[$conn->resourceId]);
        unset($this->subscriptions[$conn->resourceId]);
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
?>

Use Web Socket for Chat in Laravel 5

Now you have done all the functionality. Now you'll be in need of create a chat server .

Step3:

For create a chat server , go to your root path and create a file with named php_chat_server.php


write the following code in this file:

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Http\Controllers\ChatController;

require  'vendor/autoload.php';


$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new ChatController()
        )
    ),
    8080
);

$server->run();
?>



Use Web Socket for Chat in Laravel 5

Now you have to create a chat server.
You are done now.

Step4:

Now go to your root path and run this command:

php php_chat_server.php

This will start your chat server .

Step5:

For checking your working code, you have to go to your browser and open your localhost

For test you have to open two browser for this:

Now open your console in both browser and write this:

var conn = new WebSocket('ws://127.0.0.1:8080');

and then press enter

Use Web Socket for Chat in Laravel 5


same like this write the following lines and enter in both browser:

conn.onopen = function(e) {
  console.log("Connection established!");
};



conn.onmessage = function(e) {
  console.log(e.data);
};



conn.send(JSON.stringify({command: "subscribe", channel: "mychannel"}));

Now in only one browser's console write this code

conn.send(JSON.stringify({command: "message", message: "this is message"}));

You'll see this message at 2nd browser.

Use Web Socket for Chat in Laravel 5


You are done.

Thanks

Friday, September 18, 2015

Social site Authentication (signup and signin) in Laravel 5

Social site authentication (sign up and sign in ) in Laravel 5:

Social site Authentication (signup and signin) in Laravel 5

In this blog we are authenticate the users by twitter, facebook, google etc.
We can login and registration via using these account in our Laravel 5 app.
   
Social site Authentication (signup and signin) in Laravel 5

 1) Include package :- First we need to include socialite package to get started with Socialite, for include the package go to your composer.json file and below code to require section :-


"laravel/socialite": "~2.0"

Example :- so now your file code of require section looks like:-

"require": {
   "laravel/framework": "5.0.*",
   "laravel/socialite": "~2.0"
},


2) Register provider and facades :- to register provider you need to add this Laravel Framework Service Providers list. for this go to config/app.php and add below code to “providers” array to further use:


'Laravel\Socialite\SocialiteServiceProvider',
Example :- so now your file code of provider array section looks like:-



'providers' => [
   /* more already here */
  'Laravel\Socialite\SocialiteServiceProvider',


Facades :- To register facades go to config/app.php and add below code to “aliases” array :


'Socialize' => 'Laravel\Socialite\Facades\Socialite',
Example :- so now your file code of aliases array section looks like:-


'aliases' => [
   /* more already here */
  'Laravel\Socialite\SocialiteServiceProvider',


3) Get package from remote :- Now after add packages we need to install Socialite package in our application for this you need to run composer update command. for this pick up your laravel application directory path in CLI or terminal and run.

composer update
After install Socialite packages successfully we need to setup oauth providers credentials, routes and controllers

4) Setup OAuth providers credentials :- Now we need to create OAuth applications on providers like facebook, google, twitter, github etc. to get client id and client secret which need to authenticate with providers.
After getting client id and secret we need to setup credentials. To setup OAuth providers credentials go to config/services.php and add your provider config to existing “return” array like below



'github' => [
    'client_id' => 'your-github-app-id',
    'client_secret' => 'your-github-app-secret',
    'redirect' => 'http://your-callback-url',
],

Note:- for all provider add configuration(client id, client secret and redirect) for others like ‘facebook’, ‘google’, ‘twitter’.

5) Routes :- Now You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. so add routes in app/Http/routes.php like :-


// Redirect to github to authenticate
Route::get('github', 'AccountController@github_redirect');
// Get back to redirect url
Route::get('account/github', 'AccountController@github');

6) Controller :- so according to routes you need to set your controller function and make social authentication with use of facades like


public function redirectToProvider() {
  return Socialize::with('github')->redirect();
}


public function handleProviderCallback() {
  $user = Socialize::with('github')->user();
}

7) Retrieve user details :- After get success authenticate you can get all user details with $user object like


$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();

Now you have successfully setup-ed social authentication in laravel 5 using laravel socialite. Below we see an example of github social authentication.

Thanks

Friday, September 11, 2015

How to customize laravel 5.1 default error page

Customized Laravel 5.1 default error page:

customize laravel 5.1 default error page


For customized Laravel 5.1 default error page, we have to modify following file.

app/Exceptions/Handler.php

customize laravel 5.1 default error page


 By modification this file we can override this file :

convertExceptionToResponse

customize laravel 5.1 default error page
customize laravel 5.1 default error page
customize laravel 5.1 default error page


<?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\Debug\ExceptionHandler as SymfonyDisplayer;

class Handler extends ExceptionHandler
{
    /**
     * Convert the given exception into a Response instance.
     *
     * @param \Exception $e
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function convertExceptionToResponse(Exception $e)
    {
        $debug = config('app.debug', false);

        if ($debug) {
            return (new SymfonyDisplayer($debug))->createResponse($e);
        }

        return response()->view('errors.default', ['expection' => $e], 500);
    }
}


customize laravel 5.1 default error page


Due to doing this, we can easily modify this file :

errors.default

which is exist here:

resources/view/errors

Thanks

Friday, September 4, 2015

How to create database backup to dropbox in laravel 5

Create database backup to dropbox in Laravel 5:

For creating a database backup ,
Firstly you'll in need of pull the package through command line:


composer require backup-manager/laravel



Now we will need of pull dropbox adapter

composer require league/flysystem-dropbox

Now goto config/app.php this file & write this in providers

BackupManager\Laravel\Laravel5ServiceProvider::class,


And then publish the storage configuration file:

php artisan vendor:publish --provider="BackupManager\Laravel\Laravel5ServiceProvider"



Now Create a dropbox API

database backup to dropbox in laravel 5
For creating this, select dropbox api app as shown in image, then select 'yes' in drop box & enter application name and create app.

database backup to dropbox in laravel 5

Now in setting page you can see app key and app secret. Also genrate a access token on this page.

Now goto backup-manager.php file and add the below content.


'dropbox' => [
    'type' => 'Dropbox',
    'token' => 'your-token-here',
    'key' => 'your-key-here',
    'secret' => 'your-secret-here',
    'app' => 'your-app-name',
    'root' => '/backups',
],


 It will store backup in backups folder
database backup to dropbox in laravel

For testing this on your app, run this command on your terminal

php artisan db:backup --database=mysql --destination=dropbox --destinationPath=`date +\%s`-laravel4.sql --compression=null

 To check the file in dropbox, go to app folder.

Thanks