External API calling in Laravel by Guzzle Package

Recently I am working on a project that need to access some external API. And it’s a Laravel project, so I am looking for some package that can save my time and meet the deadline too.

 

I am using GuzzleHttp package for accessing external API and its really easy

 

Installation:

composer require guzzlehttp/guzzle:~6.0

Uses:
on your controller file just put before your class ClassName

use GuzzleHttp\Client;

 

Now call this Guzzle Client in your method

//create an instance of Client wiht base url of the API

$client = new Client(['base_uri' => 'http:127.0.0.1/path/to/api/']);

// Send a GET request to http:127.0.0.1/path/to/api/ 
// and method name is apiName 
// with api authentication (username and password)
$response = $client->request('GET', apiName', [
                 'auth' => ['username', 'password']
                 ]);

// check the response by

dd($response);

// Get the response status code

dd($response->getStatusCode());

// Get the response phase
dd($response->getReasonPhrase());

// Get all/full header
dd($response->getHeaders());

// Get specific specific entity of header, 
// here we retrive content-type
dd($response->getHeader('content-type'));

// Get api content. it return the main content the we need

dd($response->getBody()->getContents());

 

this post will continue as i go with this Guzzle package..

 

Repository – https://github.com/guzzle/guzzle

and here is the main document – http://docs.guzzlephp.org/en/latest/

 

Advertisements

Set XSRF(/CSRF) Token Globally or TokenMismatchException in Laravel 5.* (for AJAX)

Very easy (পানির লাহান) 🙂

STEP – 1:

First we have to ad a meta tag (name=”_token”) in header

<meta name=”_token” content=”{{ csrf_token() }}” />

STEP – 2:

Then add below jQuery snippet before the </body> tag. Basically here we setting up the csrf token globally for ajax request. And after this we don’t need to send the csrf token on every ajax call.

$(function () {
// SET UP CSRF TOKEN Globally for Ajax Request
$.ajaxSetup({
headers: {
‘X-XSRF-TOKEN’: $(‘meta[name=”_token”]’).attr(‘content’)
}
});
});

STEP – 3:

And finally we have to add a method on “appHttpMiddlewareVerifyCsrfToken.php” file. So, add the below method on VerifyCsrfToken.php

/**
* Determine if the session and input CSRF tokens match.
*
* @param IlluminateHttpRequest $request
* @return bool
*/
protected function tokensMatch($request)
{
$token = $request->session()->token();

$_token = $request->input(‘_token’);

$header = $request->header(‘X-XSRF-TOKEN’);

return StringUtils::equals($token, $_token) ||
($header && StringUtils::equals($token, $header));
}

Now check and let me know your comments. And I don’t mind, if you want to share this article with your friends/colleagues. Bcoz. Sharing’s Caring.  🙂

Laravel: php artisan commands

Here I am trying to list all Laravel PHP Artisan commands one by one for my reference and your too.

 

– To create and update table by migration

php artisan make:migration Create_Table_Name  -> create a new table

php artisan make:migration Update_Table_Name_Column_Name -> update table

php artisan make:migration Add_Column_Name_Table_Name  -> add a new column to a table

 

– To create a Controller

php artisan make:controller pathControllerName –resource

path = directory/place of the controller, i usually create controller directory wise . i.e.: site/SiteController – all site related controller will store here and admin/AdminController – all admin related controller will store here or test/TestController – all test related controller will store here.

ControllerName = Name of the controller

–resource = a parameter to create controller with default CRUD functions (index, create, store, show, edit, update, destroy)

 

– To create a Model

php artisan make:model pathModelName

path = directory/place of the model (optional). Same as controller

ControllerName = Name of the model

 

Update – Please visit skpaul.me for latest posts and updates

skpaul.me

Hi,

Greetings!!

Thanks for visiting my blog, I have open a blog (http://skpaul.me). So from now, you will get all latest posts and updates on http://skpaul.me.

 

Please take a look on my personal blog (http://skpaul.me), and let me know your comments and review.

 

Thanks in Advance

sk paul

http://skpaul.me

How to define Global Variable or Constant in Laravel

We often need to define global variables/constants for our application, like Status, Conditions, Countries (we can put all countries in table as it will be along array/object), also weekdays, weekends and e.t.c. vary on projects.

Status (Active, Inactive) and Conditions (Ok, Good, Better, Best) or Grade (F, C, D, A, A-, A+), so like these type of variables/constants,  we write same code multiple times. But if we set all of these as Global Variables then we can use these anytime, anywhere in application.

 

 

And here I am presenting how to define GLOBAL Variable/Constant in Laravel 5.2. (This is not the only way, but I like it)

  1. First create a file named constants.php on config directory
  2. And code some variables like below

return [

‘STATUS’ => [

1 => ‘Active’,

0 => ‘Inactive’

],

‘Conditions’ => [

1 => ‘Ok’,

2 => ‘Good,

3 => ‘Better,

4 => ‘Best’

 

],

‘GRADE’ => [

‘A+’ => ‘A+’,

‘A’ => ‘A’,

‘A-’ => ‘A-’,

‘B’ => ‘B’,

‘C’ => ‘C’,

‘D’ => ‘D’,

‘F’ => ‘F’

]

];

  1. Now, how can we use/access this Global Variables? Very easy, and we can also access these variables on view too.

Config::get(‘constants. STATUS’); // it will output status array.

Or, if we want a specific one element then

Config::get(‘constants. GRADE.F’); // output: F

  1. And lastly we can also set Global variable only for the current request. This will not persist.

Config::set(‘constants. Conditions.5’, ‘Not Stable’)

 

And finally – if you like this article please inspire me by posting a comment (at below) for the next article 😉 . And I don’t mind if you want to share among with your friends, bocz. Sharing’s Caring.

 

Credit: google, stackoverflow, Laravel.io, Laravel docs and etc.

Multiple sessions or Different logins at the same time on firefox

Multifox – is an awesome and very useful plugin for me. If you need to login multiple accounts at the same time, what did we do naturally, we used multiple browsers. But with this plugin on Firefox, you can access as many accounts as you want.

Mozilla Addons link -> click here

But if your browser’s version doesn’t support the plugin, you can try here with an old version from their website Getmultifox.com

For details and getting started check here

 

N.B.: Chrome already have this feature builtin on Settings > People > Add preson

How to print query or debug queries in Laravel

We often need to debug large queries in Laravel. And laravel have built-in functions almost for everything. Here is a simple query in laravel for example.

$data = User::where(‘status’, 1)

->select(‘name’, ‘username’, ‘email’, ‘password’)

->get();

 

but we want to see the sql query. So we have to use toSql() in the place of get() and to print the query we use dd() – die and dump function of laravel, so here is out update query

$data = User::where(‘status’, 1)

->select(‘name’, ‘username’, ‘email’, ‘password’)

// ->get()

->toSql();

And dump it

dd($data);

and the output is

“SELECT ‘name’, ‘username’, ‘email’, ‘password’ FROM user WEHRE status = 1”

 

n.b.: it also can be done by DB listen

DB::listen(function($sql) {

var_dump($sql);

});

 

Here is another option with Laravel DebugBar. It’s a full featured package and gives lots on insight of the application.

 

 

——————————————————————

Reff: https://scotch.io/tutorials/debugging-queries-in-laravel