DEV Community

Rabeea Ali
Rabeea Ali

Posted on

How to use Bitly to shorten URL with Laravel

Today's post we will see how to use Bitly to shorten URL with Laravel without any external package in easy way.

Prerequisites:

• A Laravel project.
• An Account on Bitly.

Step 1: Get token from Bitly

After login in Bitly go to this page and enter your password then click Generate token

Generate token in Bitly

Step 2: Create Service for Bitly

Now go to your Laravel project and in app directory create a folder called Services and inside it create a file called Bitly.php will contains this:

<?php

namespace App\Services;

use Throwable;
use Illuminate\Support\Facades\Http;

class Bitly
{
    public static function convert($link)
    {
        try {
            $response =  Http::accept('application/json')
                ->withToken('6ec991aXXXXXXXXXX40c996d88afa')
                ->post('https://api-ssl.bitly.com/v4/shorten', 
                    "domain" => "bit.ly",
                    "long_url" => $link,
                ]);

            $body = $response->json();

            return $body['link'];
        } catch (Throwable $e) {
            return 'invalid url';
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In withToken put your token that you get from Bitly

  • In this class I used Http which is guzzlehttp/guzzle package that comes with Laravel by default.

  • $body have several information you can use it, just dd($body) and see if they help you.

  • I used try|catch for the purpose of anyone entering an invalid URL.

For sure you can create config file for the token and put it in .env file.

Step 3: Use Bitly service

Now go to your controller and use Bitly class, something like this:

use App\Services\Bitly;

class BitlyController extends Controller
{
    public function __invoke()
    {
        $link = Bitly::convert('https://dev.to');

        return $link;
    }
}
Enter fullscreen mode Exit fullscreen mode

The $link will return the Bitly short url use it as you want.

Discussion (0)