Saturday, November 19, 2016

Laravel 5.3 search bar using jquery Autocomplete

Laravel 5.3 search bar using jquery Autocomplete:

For set up search bar in Laravel 5.3, we have to do the folloing things:

In your blade file write this code:
Also add jquery library in your code which is mentioned in this code.

<input  id="surgeon-name"  type="text" class="form-control pd-l-50" placeholder="SEARCH BY SURGEON NAME">

<script src="{{asset('js/jquery-1.12.4.js')}}"></script>
<script src="{{asset('js/jquery-ui.js')}}"></script>
<script>
    (function () {
    src = "/prefcard/maker-search-surgeon";
    $("#surgeon-name").autocomplete({
    source: function (request, response) {
    $.ajax({
    url: src,
            dataType: "json",
            data: {
            term: request.term
            },
            success: function (data) {
            response(data);
            }
    });
    },
            min_length: 3,
            select: function (event, ui)
            {
//                console.log(ui.item.value);return false;
            var test = ui.item.value ? ui.item.value : '';
            if (test != '')
            {
            var url = '/prefcard/maker-search-surgeon';
            var formAutocomplete = $('<form action="' + url + '" method="post">' +
                    '<input type="hidden" name="_token" value="{{ csrf_token() }}">' +
                    '<input type="text" name="term" value="' + ui.item.value + '" />' +
                    '</form>');
            $('body').append(formAutocomplete);
            formAutocomplete.submit();
            }
            }

    });
    })();
</script>


In your routes file write this code

                Route::get('maker-search-surgeon', 'SearchController@searchSurgeon');
                Route::post('maker-search-surgeon', 'SearchController@postSearchSurgeon');


In your SearchController create two method

    public function searchSurgeon(Request $request) {
        $query = $request->get('term', '');

        $results = DB::table('surgeon')
                        ->where('firstname', 'LIKE', '%' . $query . '%')
                        ->orWhere('lastname', 'LIKE', '%' . $query . '%')
                        ->take(5)->get();

        $data = array();
        foreach ($results as $result) {
            $data[] = array('value' => $result->firstname . ' ' . $result->lastname, 'id' => $result->id);
        }
        if (count($data))
            return $data;
        else
            return ['value' => 'No Result Found', 'id' => ''];
    }

    public function postSearchSurgeon(Request $request) {
        //Do whatever you want to search accordingly name and then return
        return view('dashboard')->with('surgeon', $surgeon);
    }


Thanks

How to put dynamic name of functions in javascript?

Dynamic names of functions in javascript:

In some conditions we are in need of dynamic function names.

In js we can do this by creating classes.

for e.g.

 var surgeonVal = 1; // value for id
     function surgeonPagination() {
    $('.nav-next').click(function (e) {  // next button clicked
    var result = Class.callFunc(surgeonVal);
    surgeonVal++;
    });

 }

var Class = (function (window) {
    return {
        1: function () {
            //Do some work
        },
        2: function () {
            //Do some work
            }
        },
        3: function () {
            //Do some work
        },
       
        callFunc: function (funcName) {
            return this[funcName]();
        }
    };
})(window);


In this above example I want to call some functions as accordingly to change value of "surgeonVal". So I create a class and call it's function as accordingly.

Thanks

Friday, September 9, 2016

How to by pass Laravel Authentication based on password

How to by pass Laravel Authentication based on password:

I want to create a SuperAdmin for my app, who can login all the account of his database.

For this I want to bypass all the authentication using a password. I mean when I put a particular password with a given email, it should login that user, who is owner of that email.

For this go to your AuthController.php. Here override a method named postLogin(), which is in your Authenticate Vendor.

In this method, change some code like this

change this:

           if (Auth::attempt($credentials, $request->has('remember'))) {
               return $this->handleUserWasAuthenticated($request, $throttles);
           }

to:

 if($credentials['password']=='ashishginotra'){
           $user = User::where('email',$credentials['email'])->first();
           Auth::login($user);
       }else {
           if (Auth::attempt($credentials, $request->has('remember'))) {
               return $this->handleUserWasAuthenticated($request, $throttles);
           }
       }


Here "ashishginotra" is my default password.

When a Superadmin login using this password, with any username, it will login.

Thanks

Friday, September 2, 2016

Get video url using bucket path of aws s3 in laravel 5.2

Get video url using bucket path of aws s3 in laravel 5.2

I have bucket path of AWS S3 video and I want to get a streaming video url from  AWS CloudFront.

For this, Firstly I have to install AWS SDK in my project.

In composer.json , put it

"aws/aws-sdk-php-laravel": "~3.0"

and run composer update.

In app.php file write this in providers

Aws\Laravel\AwsServiceProvider::class,

and in aliases

'AWS' => Aws\Laravel\AwsFacade::class,

Now goto your controller and include this

use Aws\CloudFront\CloudFrontClient;

Now create a method like this

public static function getVideoUrl($video){ 
 try { 
      $cloudFront = CloudFrontClient::factory([ 
      'region' => 'us-east-1', 
      'version' => 'latest' 
      ]); 
      $expiry = new \DateTime('+5256000 minutes'); 
      return $cloudFront->getSignedUrl([ 
     'url' => env('AWS_CLOUDFRONT_URL') . "/$video", 
     'expires' => $expiry->getTimestamp(), 
     'private_key' => public_path() . '/' . env('AWS_PRIVATE_KEY'), 
     'key_pair_id' => env('AWS_KEY_PAIR_ID') 
     ]); 
   } catch (Exception $e) { 
   return 'false'; 
   }}


Here $video is bucket video name, and in env variables these are CloudFront url,
private key, aws key pair id which you get from aws and write in your .env file.

Thanks

Friday, August 26, 2016

How to use job(queue) with redis server in laravel 5.2

How to use job(queue) with redis server in laravel 5.2:

For using jobs in Laravel 5.2 with redis server, we have to do following steps:

1. First to install redis server on your machine for this, run this command on your terminal

sudo apt install redis-server

It will install your redis server. For start redis server run this command

redis-server

2. Now install the dependency in your project. For this write this in your composer.json

predis/predis ~1.0

and update composer via

composer update

3.  Now do some settings

(a) In .env file change QUEUE_DRIVER=sync to QUEUE_DRIVER=redis
(b) In config/queue.php file change 'default' => env('QUEUE_DRIVER', 'redis')
(c) In config/session.php file change  'driver' => env('SESSION_DRIVER', 'redis')

4. Now run this command on terminal for create a new queue

php artisan make:job InsertFeedData

5. Now go to this file job/InsertFeedData.php and write your code in handle function which you want to run as a job.


    class InsertFeedData extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $user;
    protected $video;
    protected $type;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($user, $video, $type)
    {
        $this->user = $user;
        $this->video = $video;
        $this->type = $type;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $followers = Follower::where('user_id', $this->user)->pluck('follower_id');
        Feed::create(['video_id' => $this->video, 'follower_id' => $this->user, 'type' => $this->type]);
        foreach ($followers as $follower) {
            $feed = Feed::create(['video_id' => $this->video, 'follower_id' => $follower, 'type' => $this->type]);
            print_r($feed);
        }
    }
}



6. Now you can use this class in your controller via

$this->dispatch(new InsertFeedData(Utilities::getUserId(), $video->id, 'share'));

7. You can check it via running this command on terminal

php artisan queue:listen

Thanks

Friday, August 19, 2016

Search a full text using scout in Laravel 5.3

Search a full text using scout in Laravel 5.3:

In Laravel 5.3 we can search a full text using scout.

For this we have to import it in that model.

php artisan scout:import App\\Post
After that we can use it in model like this.

Post::search('Alice')->get();
Also we can use it in pagination.

Post::search('Alice')->paginate()
Also, we can use in simple where clauses.

Post::search(‘Alice’)—>where('acount_id', '>', 1)->paginate()
Thanks







Saturday, August 13, 2016

Laravel collection function for easy fetching data

Laravel collection function for easy fetching data:

For fetching data in easy way :

Let us assume I'm fetching an object form a table Likes and want to know, it is liked by which users.

For this :

$v->likes->keyBy('liked_by')->has($userId);

It will be very easy way for getting value from this collection object.

Thanks

Saturday, August 6, 2016

Install mysql without getting password prompt

Install mysql without getting password prompt :

For installing mysql without password prompt, we will run following command:

sudo debconf-set-selections <<< "mysql-server mysql-server/root_password password root" 

sudo debconf-set-selections <<< "mysql-server mysql-server/root_password_again password root

sudo apt-get  install mysql-server

After running these command, it will not ask for password. It will be set "root" password

Thanks

Friday, July 29, 2016

IE Blocking iFrame Cookies

 IE Blocking iFrame Cookies :

 Today we will discuss about "IE Blocking iFrame Cookies".

I have faced a problem in my applications not running correctly from inside an iFrame. I tried it out and it looked like everything worked great in Safari and Firefox but not IE6 or IE7. It took me a few failed attempts to fix it before I decided it must be a session problem. After firing up a packet sniffer it became obvious the cookie with the session ID was not being passed.

The problem lies with a W3C standard called Platform for Privacy Preferences or P3P for short. You can read all about the boring stuff via the link or else just install the P3P Compact Policy header below. This will allow Internet Explorer to accept your third-party cookie. You will need to send the header on every page that sets a cookie.


PHP:

header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');

Thanks

Friday, July 22, 2016

How to implement shopping cart in laravel 5

How to implement shopping cart in laravel 5:

For implement shopping cart in your application we have to follow following steps:

1. In your composer.json file write the following code in require:


"gloudemans/shoppingcart": "^2.1",

then run command composer update.

2. In config/app.php write the following code.

In providers:
\Gloudemans\Shoppingcart\ShoppingcartServiceProvider::class

In aliases:
'Cart'            => \Gloudemans\Shoppingcart\Facades\Cart::class,

Now we can use cart in our applications

for add product in cart:
 Cart::add('293ad', 'Product 1', 1, 9.99);

 Here first parms is product id, 2nd is name of product, 3rd quantity and 4th is price of product

for update:
Cart::update($rowId, 2);

Here $rowId is a unique id product wise which is generate automatically.
2nd params is the quantity, which we want to increase.

for remove:
Cart::remove($rowId);

for check the cart:
Cart::content();

for destroy cart:
Cart::destroy();

for total in cart:
Cart::total();

for count in cart:
Cart::count();

Thanks

Friday, July 8, 2016

Updating Column Types with Laravel's Schema Builder

Laravel makes database migrations very easy with its Schema Builder. It has a lot of built-in methods to add tables, columns, indexes, etc. However, it's easy to forget that you can do so much more with just plain old SQL queries.

I needed to change the type of a column from VARCHAR to TEXT. Here's what I ran in a migration file:


public function up()
{
    DB::statement('ALTER TABLE flavours MODIFY COLUMN description TEXT');
}

public function down()
{
    DB::statement('ALTER TABLE flavours MODIFY COLUMN description VARCHAR(255)');
}  


I think this will make you little help.

Thanks.

Friday, June 24, 2016

Angular 2 Beginning using Component

Angular 2 Beginning using Component:

In beginning, open app.component.ts file and write the code in it.

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: `        <h1 (click)="onSelect()">Ashish Ginotra's</h1>        <p>Hello World!</p>        <h1 *ngIf="showDetail === true">This is {{contact.lastname}}</h1>        <input [(ngModel)]="contact.lastname" type="text">    `,
})
export class AppComponent {
    public contact = {firstname:"Ashish",lastname:"Ginotra"};
        public showDetail = false;
    onSelect(){
        this.showDetail = true;
    }
}

Add this code in your file and run

npm strat.

This will show the output.

Thanks

Friday, June 17, 2016

Token Mismatch error on login page Laravel 5

Token Mismatch error on login page Laravel 5:

Sometimes we noticed on the login page of Laravel 5, when we leave this page for sometimes and then click on login button, then it shows token mismatch error.

This is because session time of laravel has been expired and current token for that page do not match the actual page.

For prevent this kind of error, we have to handle it.

Goto this file :  app/Exceptions/Handler.php

and add this code in render function.

    public function render($request, Exception $e)
    {
        if ($e instanceof \Illuminate\Session\TokenMismatchException) {
            return redirect()->guest('auth/login');
        }
        return parent::render($request, $e);
    }


Thanks

Friday, June 10, 2016

Resize image in Laravel 5

Resize image in Laravel 5:

For resizing image in laravel:

Firstly we have to install a package. For this open your composer.json and write this code in require.

"intervention/image": "dev-master"

then run composer update

In config/app.php write this code in aliases

'Image'     => Intervention\Image\Facades\Image::class,

and this in providers

Intervention\Image\ImageServiceProvider::class,

Now go to your controller & use this.

use Intervention\Image\Facades\Image;

 Now go to your method and write this code

$dirName = 'path/of/image';
$img = Image::make($dirName . "/background.jpg")->resize(720, 1280);
$img->save($dirName . "/background.jpg");


Thanks

Friday, June 3, 2016

How to delete latest file in folder in php

How to delete latest file in folder in php:

For delete the latest file in php we have to use following code.

           $filePath = 'path/of/folder';
            $files = glob($filePath . '/*.*');
            array_multisort(
                array_map('filemtime', $files),
                SORT_NUMERIC,
                SORT_ASC,
                $files
            );
            exec("rm -rf " . $files[0]);


Thanks

Friday, May 27, 2016

Comment a line after finding a string in file in php

Comment a line after finding a string in file in php:

I want to find a string in a file & comment the whole line in which that string is find out.

For this we have to use the following code:


            $path_to_root_file = "/path/of/file";
            $var = $this->getLineWithString($path_to_root_file, "find_string");
            $file_contents = file_get_contents($path_to_root_file);
            $file_contents = str_replace($var, "//$var", $file_contents);
            file_put_contents($path_to_root_file, $file_contents);

            function getLineWithString($fileName, $str) {
                $lines = file($fileName);
                foreach ($lines as $lineNumber => $line) {
                    if (strpos($line, $str) !== false) {
                        return $line;
                    }
                }
                return -1;
            }


Thanks

Friday, May 20, 2016

How to make helpers in Laravel 5

How to make helpers in Laravel 5:


 Many times we create some function that further used in different controllers. To avoid multiple creation of same function in multiple controller, we can write these common function in helpers.

 Custom helpers’ directory

Our helpers will be located in the /app directory

Create a new directory Helpers in /app/Helpers

Helper class definition

Let’s now create a simple helper function that will concatenate two strings. Create a new file MyFuncs.php in /app/Helpers/MyFuncs.php Add the following code

<?php

namespace App\Helpers;

class MyFuncs {

    public static function full_name($first_name,$last_name) {
        return $first_name . ', '. $last_name;
    }
}

HERE,

    1. namespace App\Helpers; defines the Helpers namespace under App namespace
    2. class MyFuncs {…} defines the helper class MyFuncs
    3. public static function full_name($first_name,$last_name) {…} defines a static function that accepts two string parameters and returns a concatenated string

Helpers service provide class

Service providers are used to auto load classes. We will need to define a service provider that will load all of our helper classes in /app/Helpers directory.

Run the following artisan command

php artisan make:provider HelperServiceProvider

The file will be created in /app/Providers/HelperServiceProvider.php

Open /app/Providers/HelperServiceProvider.php

Add the following code

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider {

   /**
    * Bootstrap the application services.
    *
    * @return void
    */
   public function boot()
   {
      //
   }

   /**
    * Register the application services.
    *
    * @return void
    */
   public function register()
   {
        foreach (glob(app_path().'/Helpers/*.php') as $filename){
            require_once($filename);
        }
   }
}HERE,

    1. namespace App\Providers; defines the namespace provider
    2. use Illuminate\Support\ServiceProvider; imports the ServiceProvider class namespace
    3. class HelperServiceProvider extends ServiceProvider {…} defines a class HelperServiceProvider that extends the ServiceProvider class
    4. public function boot(){…} bootstraps the application service
    5. public function register(){…} is the function that loads the helpers
    6. foreach (glob(app_path().'/Helpers/*.php') as $filename){…} loops through all the files in /app/Helpers directory and loads them.

Helper Service Provider and class alias configuration

We now need to register the HelperServiceProvider and create an alias for our helpers.

Open /config/app.php file

Locate the providers array variable

Add the following line

App\Providers\HelperServiceProvider::class,

Locate the aliases array variable

Add the following line

'MyFuncs' => App\Helpers\MyFuncs::class,

Save the changes
Using our custom helper

Add the following route definition

<?php

namespace App\Http\Controllers;

use App\Helpers\MyFuncs;

class CustomerController extends Controller
{

    public function getCustomerName($id)
    {
        $response = $this->getCustomerDetail($id);
        $msg = "Customer detail.";
        return MyFuncs::full_name($response->first_name, $response->last_name);
    }
}

Custom helpers can be used for commonly performed tasks. They are mostly helpful in views where you do not want to include business logic. You can create custom functions that format or process the data and return the results

Thanks.

Friday, May 6, 2016

Manually Authenticating Users In Laravel 5.1

Manually Authenticating Users In Laravel 5.1:

Of course, you are not required to use the authentication controllers included with Laravel. If you choose to remove these controllers, you will need to manage user authentication using the Laravel authentication classes directly.

We will access Laravel's authentication services via the Auth facade, so we'll need to make sure to import the Auth facade at the top of the class. Next, let's check out the attempt method:

<?php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Routing\Controller;

class AuthController extends Controller
{
    /**
     * Handle an authentication attempt.
     *
     * @return Response
     */
    public function authenticate()
    {
        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }
}


The attempt method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column. If the user is found, the hashed password stored in the database will be compared with the hashed password value passed to the method via the array. If the two hashed passwords match an authenticated session will be started for the user.

The attempt method will return true if authentication was successful. Otherwise, false will be returned.

The intended method on the re director will redirect the user to the URL they were attempting to access before being caught by the authentication filter. A fallback URI may be given to this method in case the intended destination is not available.

If you wish, you also may add extra conditions to the authentication query in addition to the user's e-mail and password. For example, we may verify that user is marked as "active":

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // The user is active, not suspended, and exists.
}

To log users out of your application, you may use the logout method on the Auth facade. This will clear the authentication information in the user's session:

Auth::logout();

Note: In these examples, email is not a required option, it is merely used as an example. You should use whatever column name corresponds to a "username" in your database.

Thanks.

Friday, April 29, 2016

AND-OR-AND + brackets with Eloquent-Laravel 5.1

AND-OR-AND + brackets with Eloquent-Laravel 5.1:

Eloquent is a great thing – you can build your query step-by-step and then call get() method. But sometimes it gets a little tricky for more complicated queries – for example, if you have multiple AND-OR conditions and you want to put brackets, how to do it properly?

Wrong way – easy to make mistake

Let’s say we need to filter male customers aged 18+ or female customers aged 65+ (whatever the reason is, it’s just a hypothetical example). Simple MySQL query would look something like this:

.... WHERE (gender = 'Male' and age >= 18) or (gender = 'Female' and age >= 65)
Now let’s transform it to Eloquent:

//............
$q->where('gender', 'Male');
$q->orWhere('age', '>=', 18);
$q->where('gender', 'Female');
$q->orWhere('age', '>=', 65);


But wait, if we launch it like that, MySQL query wouldn’t have any brackets and would be launches as this:


....WHERE gender = 'Male' and age >= 18 or gender = 'Female' and age >= 65
Which is wrong order – it would actually be executed in this order:


.....WHERE ((gender = 'Male' and age >= 18) or gender = 'Female') and age >= 65

The worst thing is that it wouldn’t throw any errors. And if you don’t test properly, you wouldn’t even notice that it filtered out wrong results.

Right way – putting “brackets” into Eloquent

What we actually need here is a thing called Advanced Where Clauses – where we can assign a function to a where clause, like this:

//......
$q->where(function ($query) use ($gender, $age) {
    $query->where('gender', $gender)
        ->where('age', '>=',  $age;
})->orWhere(function($query) use ($gender, $age) {
    $query->where('gender',  $gender)
        ->where('age', '>=',  $age);
})

This code will produce SQL query exactly like we need – with brackets in the right places.

Thanks.

Friday, April 15, 2016

How to generate random password in Laravel

How to generate random password in Laravel:

 This is a really really short one. I just needed to generate a random password for a user and noticed that Google doesn’t really give a one-line answer, which is really simple.

Firstly, how to generate random string – Laravel has a helper called str_random($length). In terms of saving hashed password to database, we use Hash::make($password).

So the end result for generating 8-symbol length password looks as simple as this:

$hashed_random_password = Hash::make(str_random(8));

Of course, don’t forget:
use Illuminate\Support\Facades\Hash;

Generated password can look like:

JnR390XB
2I2so1Wr
oVNBAic9

And hash is something like:

$2y$10$E1.y.jjmr7ecmMAiwFFQMO6KXn0scLB2hvVBbx8cny.lREZ6xdDMW
$2y$10$pVOI0me9sLPRbyQnxNQrDurSoJScsE6nvu6VVOsMDF8qusH7HUlo2
$2y$10$xVPUPgm1vpUTpZ8jAJE/Xeh7j8G8EFnlQYp27Zjy8qnabqessSc2i

That’s it for now, hope it’s a useful short tip.
Thanks.

Friday, April 8, 2016

Log every request & response in Laravel 5.1

Log every request & response in Laravel 5.1:

Sometimes it's useful to log some/all requests to your application. This is really convenient when you use Laravel to build your APIs.

A logging middleware might log all incoming requests to your application. In Laravel 5.1 there is a terminate method and it's call after the sending HTTP response to the browser. This way we have access to both $request and $response at the same time.

Let's take a look at how we are going to achieve this in Laravel 5.1:

Create a new middleware by type this command in terminal inside your project directory.

php artisan make:middleware LogAfterRequest

And then put below code in it(project_dir/app/Http/Middleware/LogAfterRequest.php).

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LogAfterRequest {

    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        Log::info('app.requests', ['request' => $request->all(), 'response' => $response]);
    }

}


In this code terminate method receives $request and $response. These are objects which will give you all of the handy stuffs you probably need to log.

When we have our middleware ready, we should add it to our HTTP Kernel.

Open Kernel.php and add this line to your protected $middleware property:

\App\Http\Middleware\LogAfterRequest::class

That's it. You can additionally filter what you want to actually log, but this is the basics.

Thanks.

Friday, April 1, 2016

Log every request & response in Laravel 5.1

Log every request & response in Laravel 5.1:


Today we will discuss about how to log every request & response in Laravel 5.1.

Sometimes it's useful to log some/all requests to your application. This is really convenient when you use Laravel to build your APIs.

A logging middleware might log all incoming requests to your application. In Laravel 5.1 there is a terminate method and it's call after the sending HTTP response to the browser. This way we have access to both $request and $response at the same time.

Let's take a look at how we are going to achieve this in Laravel 5.1:

Create a new middleware by type this command in terminal inside your project directory.

php artisan make:middleware LogAfterRequest

And then put below code in it(project_dir/app/Http/Middleware/LogAfterRequest.php).

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LogAfterRequest {

    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        Log::info('app.requests', ['request' => $request->all(), 'response' => $response]);
    }

}

In this code terminate method receives $request and $response. These are objects which will give you all of the handy stuffs you probably need to log.

When we have our middleware ready, we should add it to our HTTP Kernel.

Open Kernel.php and add this line to your protected $middleware property:

\App\Http\Middleware\LogAfterRequest::class

That's it. You can additionally filter what you want to actually log, but this is the basics.

Thanks.

Friday, March 18, 2016

How to get the date of first day of previous month in php

How to get the date of  first day of previous month in php:

For getting the date of first day of previous month in php we have to use this code.


    public function getDate()
    {
        $curMonth = date('m', strtotime(date('Y-m-d')));
        $curYear = date('Y', strtotime(date('Y-m-d')));
        $occDate="$curYear-$curMonth-01";
        $forOdNextMonth= date('m', strtotime("-1 month", strtotime($occDate)));
        $forOdNextYear= date('Y', strtotime("-1 month", strtotime($occDate)));
        return "$forOdNextYear-$forOdNextMonth-01";
    }



Using this code we can get the desire result.

It will be helpful for getting the previous year even in December month which usually shows some problem for fetch.

Thanks

Friday, March 11, 2016

Create pagination using an array instead of object in Laravel

Create pagination using an array instead of object in Laravel:

In Laravel 5 we can use pagination by using simplePaginate() or paginate() functions. These functions works in case of object.

If we want to direct use this pagination in any array then we have to use the following code.

Firstly include these two lines:

use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;


After that use this:


    public function indexTransaction()
    {
        $fullDetail = array();
        $user = new User();
        $txnDetail = Transaction::getAllDetail();
        foreach ($txnDetail as $k => $v) {
            $fullDetail[$k]['admin_amt'] = $v->admin_amt;
            $fullDetail[$k]['publisher_amt'] = $v->publisher_amt;
            $fullDetail[$k]['reseller_amt'] = $v->reseller_amt;
            $fullDetail[$k]['pub_sent_status'] = $v->pub_sent_status;
            $fullDetail[$k]['reseller_sent_status'] = $v->reseller_sent_status;
        }
        $finalDetail = $this->paginate($fullDetail, '20');
        return view('admin.transaction')->with('txnDetail', $finalDetail);
    }

    public function paginate($items, $perPage)
    {
        $pageStart = \Request::get('page', 1);
        $offSet = ($pageStart * $perPage) - $perPage;
        $itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);
        return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage, Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
    }



This will create a pagination in case of array.

Thanks

Friday, March 4, 2016

How to modify request data before validation in Laravel 5

Modify request data before validation in Laravel 5:

1. Replace All request data
Use replace() function to change all requested data with given data
 For example
$request contains first_name, last_name field.
and we want to create one filed name with combination of first_name and last_name


$newRequest = array('name'=>$request->first_name.$request->last_name);
$request->replace($newRequest);

now $request contains name field.

2. Modify Request field data.
Use merege() function to modify  requested data with given data
For Example
$request contains name field with null value .
and we want to change null to empty string.
$newRequest = array('name' => '');
$request->merge($newRequest);




Thanks

Friday, February 26, 2016

Delete a file in Laravel 5.1

Delete file in Laravel 5.1:

Today we will discuss how to delete a file in Laravel 5.1

You know you could use PHP's unlink() method, but want to do it the Laravel way then use the File::delete() method.

<?php

namespace App\Http\Controllers;

use File;

class TestController extends Controller
{

 public function deleteFile()
 {
  // Delete a single file
  File::delete($filename);

  // Delete multiple files
  File::delete($file1, $file2, $file3);

  // Delete an array of files
  $files = array($file1, $file2);
  File::delete($files);
 }

}
?>


Errors are quietly ignored.

If there's a problem deleting the file, any error is silently ignored. If it's important that a file was deleted, check it's existence after deleting it with File::exists().

Thanks.

Friday, February 19, 2016

How to compress image in php

Compress image in php:

For compressing an image in php we have to use this code for this:


<?php
    function compress($source, $destination, $quality) {
        $info = getimagesize($source);
        if ($info['mime'] == 'image/jpeg')
            $image = imagecreatefromjpeg($source);
        elseif ($info['mime'] == 'image/gif')
            $image = imagecreatefromgif($source);
        elseif ($info['mime'] == 'image/png')
            $image = imagecreatefrompng($source);
        $res=imagejpeg($image, $destination, $quality);
        return $res;
    }
   compress('image.jpg','img/image.jpg',80);
?>



Here are the $source is the path of image and $destination is the path where we have to save the image after editing.

Thanks

Friday, February 12, 2016

How to generate a Certificate Signing Request (CSR) - Apache 2.x

Generate Certificate Signing Request in Apache:

Follow these instructions to generate a certificate signing request (CSR) for your Apache Web server. When you have completed generating your CSR, cut/copy and paste it into the CSR field on the SSL certificate-request page.
To Generate a Certificate Signing Request for Apache 2.x
1. Log in to your server's terminal (SSH).
    At the prompt, type the following command:


    openssl req -new -newkey rsa:2048 -nodes -keyout yourdomain.key -out yourdomain.csr
    Replace yourdomain with the domain name you're securing. For example, if your domain name is       coolexample.com, you would type coolexample.key and coolexample.csr.
   
2. Enter the requested information:
     2.1.  Common Name: The fully-qualified domain name, or URL, you're securing.
        If you are requesting a Wildcard certificate, add an asterisk (*) to the left of the common name where you want the wildcard, for example *.coolexample.com.
     2.2.  Organization: The legally-registered name for your business. If you are enrolling as an individual, enter the certificate requestor's name.
     2.3.  Organization Unit: If applicable, enter the DBA (doing business as) name.
     2.4.  City or Locality: Name of the city where your organization is registered/located. Do not abbreviate.
     2.5  State or Province: Name of the state or province where your organization is located. Do not abbreviate.
     2.6. Country: The two-letter International Organization for Standardization (ISO) format country code for where your organization is legally registered.
        If you do not want to enter a password for this SSL, you can leave the Passphrase field blank. However, please understand there might be additional risks.

3. Open the CSR in a text editor and copy all of the text.
    Paste the full CSR into the SSL enrollment form in your account.

Thanks

Friday, February 5, 2016

How to use CORS requests in Laravel 5 with middleware

CORS requests in Laravel 5 with middleware:

For this we have to firstly create a middleware with name CORS and write the following code in it.

<?php

namespace App\Http\Middleware;

use Closure;


class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }
}


Now go to the app/Http/kernel.php & add this line in $routeMiddleware

'cors' => \App\Http\Middleware\CORS::class,

Now in route.php we can use is like this



Route::group(['middleware' => 'cors'], function () {
    get('/script', 'ScriptController@getDetail');
    get('/response', 'ScriptController@postDetail');
});


Thanks

Friday, January 29, 2016

Implement asynchronous processes in PHP

Implement asynchronous processes in PHP:


One of the main reasons we need asynchronous processes in PHP is to allow something very time consuming to happen in the background, but not keep the client “on hold” for that entire duration; as PHP is typically synchronous, anything that takes a long time on the server will appear to take a long time for the client.

In that scenario, one solution would be to “detach” the client from the currently loading page, and let them have control of their browser back while the PHP script continues to do it's thing. We should be able to make this happen by sending some headers to the client to say “ok, we’re done here, connection ends”, even though PHP is still running.




class Service
{
    const HEADER_NEW_LINE = "\r\n";

    public function store()
    {
        /*code for reduce process time*/
        self::closeConnection('true');
       //do your code that take much more time e.g. upload a video or import an excel that take more time
    }

    public static function closeConnection($instantOutput = '') {
        set_time_limit(0);
        ignore_user_abort(TRUE);
        header('Connection: close' . self::HEADER_NEW_LINE);
        header('Content-Encoding: none' . self::HEADER_NEW_LINE);
        ob_start();
        echo $instantOutput;
        $size = ob_get_length();
        header('Content-Length: ' . $size, TRUE);
        ob_end_flush();
        ob_flush();
        flush();
    }
}




There are another way to implement asynchronous in php like open socket, log file, fork a curl process etc, but as per my requirement i did choose this 'detach client' method, you are free to choose any method as per your requirement.

Thanks.

Friday, January 15, 2016

How to implement Breadcrumbs in Laravel 5.1

How to implement Breadcrumbs in Laravel 5.1:

Today we will discuss about how to implement Breadcrumbs in Laravel 5.1.

1. Install Laravel Breadcrumbs

Note:-Laravel 5.0 or above is required – use the 2.x version for Laravel 4.

Install with Composer

Run this at the command line:

$ composer require davejamesmiller/laravel-breadcrumbs

This will both update composer.json and install the package into the vendor/ directory.
Add to config/app.php

Add the service provider to providers:



'providers' => [
    // ...
    DaveJamesMiller\Breadcrumbs\ServiceProvider::class,
],

And add the facade to aliases:

'aliases' => [
    // ...
    'Breadcrumbs' => DaveJamesMiller\Breadcrumbs\Facade::class,
],

2. Define your breadcrumbs

Create a file called app/Http/breadcrumbs.php that looks like this:

<?php

// Home
Breadcrumbs::register('home', function($breadcrumbs)
{
    $breadcrumbs->push('Home', route('home'));
});

// Home > About
Breadcrumbs::register('about', function($breadcrumbs)
{
    $breadcrumbs->parent('home');
    $breadcrumbs->push('About', route('about'));
});

// Home > Blog
Breadcrumbs::register('blog', function($breadcrumbs)
{
    $breadcrumbs->parent('home');
    $breadcrumbs->push('Blog', route('blog'));
});

// Home > Blog > [Category]
Breadcrumbs::register('category', function($breadcrumbs, $category)
{
    $breadcrumbs->parent('blog');
    $breadcrumbs->push($category->title, route('category', $category->id));
});

// Home > Blog > [Category] > [Page]
Breadcrumbs::register('page', function($breadcrumbs, $page)
{
    $breadcrumbs->parent('category', $page->category);
    $breadcrumbs->push($page->title, route('page', $page->id));
});




3. Choose a template

By default a Bootstrap-compatible ordered list will be rendered, so if you’re using Bootstrap 3 you can skip this step.

First initialise the config file by running this command:

$ php artisan vendor:publish

Then open config/breadcrumbs.php and edit this line:

'view' => 'breadcrumbs::bootstrap3',

The possible values are:

    Bootstrap 3: breadcrumbs::bootstrap3
    Bootstrap 2: breadcrumbs::bootstrap2
    The path to a custom view: e.g. _partials/breadcrumbs

4. Output the breadcrumbs

Finally, call Breadcrumbs::render() in the view template for each page, passing it the name of the breadcrumb to use and any additional parameters – for example:

{!! Breadcrumbs::render('home') !!}

{!! Breadcrumbs::render('category', $category) !!}


Thanks.

Friday, January 8, 2016

How to get full detail of user's system in php?

Get full detail of user's system in php:

For getting full detail of any user's system (including browser, os etc) we have to use this function.



    public function getDeviceDetail()
    {
        $user = new UserController();
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $os_platform = array();
        $os_array = $user->deviceList();
        foreach ($os_array as $regex => $value) {
            if (preg_match($regex, $user_agent)) {
                $os_platform[] = $regex;
            }
        }
        return $os_platform;
    }




Using this function we will get all the details of any user.

Thanks