How To: Post Instagram via Laravel Command

Riza
4 min readNov 18, 2022

--

Post picture/image to instagram via laravel command is usefull for anyone who want to learn programming or a programmer or everyone is going to scheduling post image/video using laravel sceduling to automatic all activity their bussiness online post.

First, install laravel version 8 with following command via composer:

composer create-project laravel/laravel:^8.0 post-ig-app

Then, create a controller using artisan like this:

php artisan make:controller PostIGController

And then, open file PostIGController.php in app/Http/Controllers. Add logic to handle post picture to IG account.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostIGController extends Controller
{
public function index()
{
$imagesEndpointFormat = 'https://graph.facebook.com/v5.0/{ig-user-id}/media?image_url={image-url}&caption={caption}&access_token={access-token}';
$videoEndpointFormat = 'https://graph.facebook.com/v5.0/{ig-user-id}/media?video_url={video-url}&media_type&caption={caption}&access_token={access-token}';
$publishMediaEndpointFormat = 'https://graph.facebook.com/v5.0/{ig-user-id}/media_publish?creation_id={creation-id}&access_token={access-token}';
$userApiLimitEndpointFormat = 'https://graph.facebook.com/v5.0/{ig-user-id}/content_publishing_limit';
$mediaObejctStatusEndpointFormat = 'https://graph.facebook.com/v5.0/{ig-container-id}?fields=status_code';

$end_point = \Config::get('defines.end_point');
$ig_id = \Config::get('defines.ig_id');
$accessToken = \Config::get('defines.access_token');
$imageMediaObjectEndpoint = $end_point . $ig_id . '/media';
$imageMediaObjectEndpointParams = array( // POST
'image_url' => 'https://via.placeholder.com/300/FFFF00/000000?Text=Digital.com',
'caption' => 'This image was posted through the Instagram Graph API with a script I wrote!..
Lovers Ulama/scholars and Habaib.
#instagram #graphapi #instagramgraphapi #code #coding #programming #php #api #webdeveloper #codinglife #developer #coder #tech #developerlife #webdev #youtube #instgramgraphapi
',
'access_token' => $accessToken
);
$imageMediaObjectResponseArray = $this->makeApiCall($imageMediaObjectEndpoint, 'POST', $imageMediaObjectEndpointParams);
// set status to in progress
$imageMediaObjectStatusCode = 'IN_PROGRESS';

while ($imageMediaObjectStatusCode != 'FINISHED') { // keep checking media object until it is ready for publishing
$imageMediaObjectStatusEndpoint = $end_point . $imageMediaObjectResponseArray['id'];
$imageMediaObjectStatusEndpointParams = array( // endpoint params
'fields' => 'status_code',
'access_token' => $accessToken
);
$imageMediaObjectResponseArray = $this->makeApiCall($imageMediaObjectStatusEndpoint, 'GET', $imageMediaObjectStatusEndpointParams);
$imageMediaObjectStatusCode = $imageMediaObjectResponseArray['status_code'];
sleep(5);
}

// publish image
$imageMediaObjectId = $imageMediaObjectResponseArray['id'];
$publishImageEndpoint = $end_point . $ig_id . '/media_publish';
$publishEndpointParams = array(
'creation_id' => $imageMediaObjectId,
'access_token' => $accessToken
);
$publishImageResponseArray = $this->makeApiCall($publishImageEndpoint, 'POST', $publishEndpointParams);

return view('post', [
'imagesEndpointFormat' => $imagesEndpointFormat,
'imageMediaObjectResponseArray' => $imageMediaObjectResponseArray,
'publishMediaEndpointFormat' => $publishMediaEndpointFormat,
'publishImageResponseArray' => $publishImageResponseArray
]);
}

function makeApiCall($endpoint, $type, $params)
{
$ch = curl_init();

if ('POST' == $type) {
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_POST, 1);
} elseif ('GET' == $type) {
curl_setopt($ch, CURLOPT_URL, $endpoint . '?' . http_build_query($params));
}

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

return json_decode($response, true);
}
}

Okey, before all. Add config as defines.php in folder config. This is content of it.

<?php

return [
'end_point' => env('ENDPOINT_BASE')
'access_token' => env('ACCESS_TOKEN'),
'ig_id' => env('IG_ACCOUNT_ID')
];

As we have know, the defines.php file takes value from file .env. So, let’s you fill all configuration in your .env file.

And then, create file post.blade.php in folder resources/views. Write code like this.

<!DOCTYPE html>
<html>

<head>
<title>
Instagram Graph API Content Publishing
</title>
<style>
body {
font-family: 'Helvetica';
}

.raw-response {
width: 100%;
height: 100px;
}
</style>
</head>

<body>
<h1>Instagram Graph API Content Publishing</h1>
<hr />
<h3>Media Object Image Endpoint: <?php echo $imagesEndpointFormat; ?></h3>
<h3>Raw Response</h3>
<textarea class="raw-response">
<?php print_r($imageMediaObjectResponseArray); ?>
</textarea>
<hr />
<h3>Publish Image Endpoint: <?php echo $publishMediaEndpointFormat; ?></h3>
<h3>Raw Response</h3>
<textarea class="raw-response">
<?php print_r($publishImageResponseArray); ?>
</textarea>
<hr />

</body>

</html>

And finnaly, let’s us create custom command to execute post instagram controller to accomplish publish image on our instagram account. Therefore, do this following instruction.

php artisan make:command PostIGCommand

After that, let’s us open PostIGCommand.php file in app/Console/Commands. Add following code to finish it.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Controllers\PostIGController;

class PostInstagram extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'post:ig';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Post picture to Instagram Bussiness Account via laravel command';

/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}

/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$cek = new PostIGController();
$this->info($cek->index());
}
}

And to try , do this.

php artisan post:ig

After that, the result on command will have following produced.

<!DOCTYPE html>
<html>

<head>
<title>
Instagram Graph API Content Publishing
</title>
<style>
body {
font-family: 'Helvetica';
}

.raw-response {
width: 100%;
height: 100px;
}
</style>
</head>

<body>
<h1>Instagram Graph API Content Publishing</h1>
<hr />
<h3>Media Object Image Endpoint: https://graph.facebook.com/v5.0/{ig-user-id}/media?image_url={image-url}&caption={caption}&access_token={access-token}</h3>
<h3>Raw Response</h3>
<textarea class="raw-response">
Array
(
[status_code] => FINISHED
[id] => xxxxxxxxxxxxxxxxx
)
</textarea>
<hr />
<h3>Publish Image Endpoint: https://graph.facebook.com/v5.0/{ig-user-id}/media_publish?creation_id={creation-id}&access_token={access-token}</h3>
<h3>Raw Response</h3>
<textarea class="raw-response">
Array
(
[id] => xxxxxxxxxxxxxxxxx

)
</textarea>
<hr />

</body>

</html>

And if we go to our page instagram, we will see the recently post picture successfully, like this.

Thank you for reading! If you enjoyed this article:

Clap it ! Share it! Follow Me in Medium!

Have a sweet dreams!!!

--

--