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



composer require guzzlehttp/guzzle:~6.0

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:']);

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

// check the response by


// Get the response status code


// Get the response phase

// Get all/full header

// Get specific specific entity of header, 
// here we retrive content-type

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



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/


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
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


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.

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’)



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()


And dump it


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) {




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


Laravel 5.1: Unsupported operand types (FatalErrorException in …)

Ok. When I am upgrading my application from Laravel 5.0 to 5.1 I get an falat error that this showing “Unsupported operand types”


What did I do on Laravel 5.0:

I add two array with in + operator, and that is the problem. So, I looking for solution and get this on Laracast

$item_list = array(”=>’–Select–‘) + Model::lists(‘name’, ‘id’);

what do I do on Laravel 5.1

this is a quick fix: just add another function at the end of the line ( and just before of the ; )  ->toArray()

so, here is the updated code

$item_list = array(”=>’–Select–‘) + Model::lists(‘name’, ‘id’)->toArray();


Why this: the reason for this update.

In 5.1, in Colleciton.php, it uses this:

return new static(Arr::pluck($this->items, $value, $key));

instead of this:

return array_pluck($this->items, $value, $key);

which, in turn does this:

return (Arr::pluck($this->items, $value, $key));

So it looks like the new behavior is to return a collection vs an array, thus the need to specify the toArray()


credit: @scottlaurent

Laravel 5 tricks (rough for me)

I need these few thing when I am working on Laravel 5. You can add more by comment..


How to install packages by composer
adding a package: composer require vendor_name/package_name
removing a package: composer remove vendor_name/package_name

adding form and html package:
composer require illuminate/html

for pdf package (reporting: generating pdf):
composer require barryvdh/laravel-snappy
composer require barryvdh/laravel-dompdf

How to desable default dates (created_at and published_at) on form in Laravel:
You can disable Localy
1. set public $timestamps = false; in YourModel.php file

Or you can disable globaly
at line no. 65
in Sublime press Ctrl+P and type model.php and u can see the above file link and select the file Model.php
and update the $timestamps variable to false;

* Indicates if the model should be timestamped.
* @var bool
// public $timestamps = true;
public $timestamps = false;

Yahoo.. you are done.

chnaging the storage path in Laravel:
there are two methods to uoload files
1. Normal

2. Using Storage API
first add these line above ControllerName
// — for file system
use IlluminateSupportFacadesStorage;
use IlluminateSupportFacadesFile;

and then..
$file = Request::file(‘filefield’);
$extension = $file->getClientOriginalExtension(); // get the file’s extension
Storage::disk(‘local’)->put($file->getFilename().’.’.$extension,  File::get($file)); // uplaoding file to your local directory
$entry->mime = $file->getClientMimeType(); // get the file’s MIME type
$entry->original_filename = $file->getClientOriginalName(); // get the file name
MySQL Query Functions:
creat($inputs) : for inserting data to a table
all(): for getting all data.
lists(‘id’, ‘name’) : for getting list from a table. argument/s needed.

print last MySQL query in Laravel for debuging
enable log

Last Inserted Row/ ID:

Path in Laravel
App Path:
app_path() : get tihe full path of the app directory
base_path(): get the path to the root directory of the application
public_path(): get the full path of the publich directory
storage_path(): get the storage (app/storage) directory path


To create the migration, via the command line, in the root folder of your application, simply type:
php artisan migrate:make create_users_table ––create=users

This will automatically create a migrations file inside of yourapp/database/migrations folder. Let’s take a look at the newly created file.

To run the migration andcreate our user table, use the command line again and run:
php artisan migrate
Just like that, the command will use the up() function and bam! We have our users table with all the columns we wanted.
Reverting Migrations: Now if you wanted to rollback migrations, we could use php artisan migrate:rollback or php artisan migrate:reset.

Adding CSS Files:
{{ HTML::style(path-to-css-dir/file-name.css’)}}
{{ HTML::style(‘css/main.css’)}}

Working With Session:
<p class=”alert”>{{ Session::get(‘message’) }}</p>

FatalErrorException in EloquentUserProvider.php line 122: Class ‘AppUser’ not found
Ans =>
Need to update config/auth.php file. Change
‘model’ => ‘AppUser’
‘model’ => ‘AppModelsUser’

clean cache: How to clean cache in laravel?
php artisan cache:clear


How to delete file in laravel 5?


How to delete directory/folder in Laravel 5?