Laravel with Packages | How to create a URL shortener using Laravel?

Raviya Technical
4 min readOct 4, 2022

Today, I would like to share with you how to generate a short URL in laravethe l application. sometimes we need to make shortened URL strings instead of lona g URL. in this tutorial I will show you step by step how to create shorten a URL in laravel 5 without any package. you can write your script function for genthe erator short link in laravel 6, laravel 7, laravel 8, and laravel 9.

If you are working with SMS or somewhere sharing with limited chacharactersd at that time if you need to share any URL or link then you must have to generate a shortener URL. In your project it’s needed many times then you must have to implement a module that can help to generate Ua RL shortener with your website domain.

You need to just follow step by step this tutorial, you will get a very simple module for generating short llinksin laravel 5. I will also give you a free download whole script.

Preview:

Laravel with Packages | How to create a URL shortener using Laravel?

Step 1: Install Laravel 5

In this step, if you haven’t a laravel 5 application setup then we have to get a fresh laravel 5 application. So run bthe elow command and get a clean fresh laravel 5 application.

composer create-project --prefer-dist laravel/laravel blog

Step 2: Create Table

we are going to create from scratch application to create short links. so we have to create migration for “short_links” table using Laravel PHP artisan command, so first fire bellow command:

php artisan make:migration create_short_links_table

After this command you will find one file in the following path “database/migrations” and you have to put the below code in your migration file for creating the short_links table.

<?phpuse Illuminate\Support\Facades\Schema;use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreateShortLinksTable extends Migration{/*** Run the migrations.** @return void*/public function up(){Schema::create('short_links', function (Blueprint $table) {$table->bigIncrements('id');$table->string('code');$table->string('link');$table->timestamps();});}/*** Reverse the migrations.** @return void*/public function down(){Schema::dropIfExists('short_links');}}

Now you have to run this migration by the following command:

php artisan migrate

Step 3: Create a Model

In this step, now we should create a new model as ShortLink. So run the below command and create a new model. run below command:

php artisan make:model ShortLink

app/ShortLink.php

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class ShortLink extends Model{/*** The attributes that are mass assignable.** @var array*/protected $fillable = ['code', 'link'];}

Step 4: Create Route

In this step, we need to create a route for the layout file and another one for storing data. so open your routes/web.php file and add the following route.

routes/web.php

Route::get('generate-shorten-link', 'ShortLinkController@index');Route::post('generate-shorten-link', 'ShortLinkController@store')->name('generate.shorten.link.post');Route::get('{code}', 'ShortLinkController@shortenLink')->name('shorten.link');

Step 5: Create Controller

At this point, now we should create a new controller as ShortLinkController. this controller will manage the layout and store data in the database, so put the below content in the controller file:

app/Http/Controllers/ShortLinkController.php

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\ShortLink;class ShortLinkController extends Controller{/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function index(){$shortLinks = ShortLink::latest()->get();return view('shortenLink', compact('shortLinks'));}/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function store(Request $request){$request->validate(['link' => 'required|url']);$input['link'] = $request->link;$input['code'] = str_random(6);ShortLink::create($input);return redirect('generate-shorten-link')->with('success', 'Shorten Link Generated Successfully!');}/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function shortenLink($code){$find = ShortLink::where('code', $code)->first();return redirect($find->link);}}

Step 6: Create a View

In the Last step, let’s create shortenLink.blade.php(resources/views/shortenLink.blade.php) for the layout and we will write the design code here and put the following code:

resources/views/shortenLink.blade.php

<!DOCTYPE html><html><head><title>How to create url shortener using Laravel? - ItSolutionStuff.com</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /></head><body><div class="container"><h1>How to create url shortener using Laravel? - ItSolutionStuff.com</h1><div class="card"><div class="card-header"><form method="POST" action="{{ route('generate.shorten.link.post') }}">@csrf<div class="input-group mb-3"><input type="text" name="link" class="form-control" placeholder="Enter URL" aria-label="Recipient's username" aria-describedby="basic-addon2"><div class="input-group-append"><button class="btn btn-success" type="submit">Generate Shorten Link</button></div></div></form></div><div class="card-body">@if (Session::has('success'))<div class="alert alert-success"><p>{{ Session::get('success') }}</p></div>@endif<table class="table table-bordered table-sm"><thead><tr><th>ID</th><th>Short Link</th><th>Link</th></tr></thead><tbody>@foreach($shortLinks as $row)<tr><td>{{ $row->id }}</td><td><a href="{{ route('shorten.link', $row->code) }}" target="_blank">{{ route('shorten.link', $row->code) }}</a></td><td>{{ $row->link }}</td></tr>@endforeach</tbody></table></div></div></div></body></html>

Now we are ready to run our example so run the below command to quick run:

php artisan serve

Now you can open the below URL on your browser:

http://localhost:8000/generate-shorten-link

I hope it can help you…

--

--