Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

short-url
laravel
communitycreator

How to shorten a URL in Laravel

Chinweuba Elijah Azubuike
widget

Ever wanted to share a post from your blog and the URL was just too long, so you want to shorten your URL for clean representation?

In this shot, I will teach you an example of how to shorten a URL.

We will be installing a package to our application called short-URL.

Must have: PHP 8, Laravel 8, BC Math or GMP PHP extensions

Installation

Run the below composer command:

composer require ashallendesign/short-url

Publish config

Using the below code, we will publish the config file, which will also generate a migration file for our database.

php artisan vendor:publish --provider="AshAllenDesign\ShortURL\Providers\ShortURLProvider"

Migrate

We will migrate the database using the generated migration file with the below command:

php artisan migrate

Usage and example

From your controller, call the builder() class of the package and pass a ->make() method, like so:

$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->make();// place the original URL inside the destination().
$shortURL = $shortURLObject->default_short_url;//grab the shorten URL

As explained in the inline code comment, inside of the destination(), place the URL you wish to shorten, then finally grab the shortened URL.

RELATED TAGS

short-url
laravel
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring