Saturday, February 25, 2017

Convert to camel case and snake case in php

Convert to camel case and snake case in php:

In php, if we want to convert camel case to snake case and vise versa then we have to use following methods:

public static function convertToCamelCase($array) {
        $converted_array = [];
        foreach ($array as $old_key => $value) {
            if (is_array($value)) {
                $value = static::convertToCamelCase($value);
            } else if (is_object($value)) {
                if (method_exists($value, 'toArray')) {
                    $value = $value->toArray();
                } else {
                    $value = (array) $value;
                }
                $value = static::convertToCamelCase($value);
            }
            $converted_array[camel_case($old_key)] = $value;
        }
        return $converted_array;
    }


public static function convertToSnakeCase($array) {
        $converted_array = [];
        foreach ($array as $old_key => $value) {
            if (is_array($value)) {
                $value = static::convertToSnakeCase($value);
            } else if (is_object($value)) {
                if (method_exists($value, 'toArray')) {
                    $value = $value->toArray();
                } else {
                    $value = (array) $value;
                }
                $value = static::convertToSnakeCase($value);
            }
            $new_key = ltrim(strtolower(preg_replace('/[A-Z]/', '_$0', $old_key)), '_');
            $converted_array[$new_key] = $value;
        }
        return $converted_array;
    }



This will help for this.

Laravel 5.4 validation for age lesser than 18

Laravel 5.4 validation for age lesser than 18:

In laravel 5.4 validation we have only min & max value , which counts the number.

If in such case we have to validate age then this will not help.

For this we have to use regex like this:

            'age' => ['required','numeric','regex:/^(?:[1-9]\d{2,}+|[2-9]\d|1[89])$/i'],

It will not allow age lesser than 18 

Thanks

Laravel multi select box get old value

Laravel multi select box get old value:

Hi, Some time we want to get old values in laravel (when there is some validation apply on a form.).

In this case, genrally we are unable to get old value for a multiple select box.

For this use this code:

<select name="tribe[]" id="tags" class="form-control" multiple>
                                    @if (is_array(old('tribe')))
                                    @foreach ($tribes as $tribe)
                                    <option value="{{ $tribe->id }}" <?php if(in_array($tribe->id, old('tribe'))) {echo 'selected';} ?> >{{ $tribe->name }}</option>
                                    @endforeach
                                    @else
                                    @foreach ($tribes as $tribe)
                                    <option value="{{ $tribe->id }}" >{{ $tribe->name }}</option>
                                    @endforeach
                                    @endif
                                </select>


This will help for get old values in multiple select box.

Thanks

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