How to create url shortener in Laravel 8?

Today, i would like to share you How to create url shortener in Laravel in this post give you and watch this type of this post and provide your original link to shortner url generate online. First of all, we need to add this to our project:


You can see the posts route looks like this: get all posts It’s composed by a form with some form-like interface (if you wanna learn more about form API, take a look at Laravel Form tutorial) and then calls a different controller. How to create url shortener in Laravel ?.From now on, let’s see how to create a simple new url shortener using Laravel 5. To do this, we need to create our middleware:
Then, we need to use curl command to generate some actual short urls. The final code looks like this:

Preview of :How to create url shortener in Laravel:

How to create url shortener in Laravel,how to generate url shortener in laravel php

Step 1:For How to create url shortener in Laravel. Install Laravel 8

In this step, create new fresh project in your file

laravel new blog

Step 2: Create Table

In this step create table in your localhost or live server database and get this output and give your mark has been.

php artisan make:migration create_sort_links_tbl

database/migrations/CreateSortLinksTbl.php

<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class CreateSortLinksTbl extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sort_links', function (Blueprint $table) {
            $table->Increments('Id');
            $table->string('Codes');
            $table->string('Url');
            $table->timestamps();
        });
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('short_links');
    }
}

Now you have to run this migration by following command:

php artisan migrate

Step 3: Create Model

In this step, run bellow command:

php artisan make:model SortLink

app/SortLink.php

<?php
   
namespace App;
   
use Illuminate\Database\Eloquent\Model;
   
class SortLink extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'Codes', 'Url'
    ];
}

Step 4: Create Route

In this is step create route for layout file and another. so open your routes/web.php file and add following route.

routes/web.php

Route::get('generate-sorten-link', 'SortLinkController@index');
Route::post('generate-sorten-link', 'SortLinkController@insert')->name('generate.sorten.link.post');
   
Route::get('{code}', 'SortLinkController@sortenLink')->name('sorten.link');

Step 5: Create Controller

app/Http/Controllers/SortLinkController.php

<?php
  
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\SortLink;
  
class SortLinkController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $sortLinks = SortLink::latest()->get();
   
        return view('sortenLink', compact('sortLinks'));
    }
     
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function insert(Request $request)
    {
        $request->validate([
           'Url' => 'required|url'
        ]);
   
        $input['Url'] = $request->Url;
        $input['Codes'] = str_random(6);
   
        ShortLink::create($input);
  
        return redirect('generate-sorten-link')
             ->with('success', 'Sorten Link Created Successfully!');
    }
   
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function sortenLink($Codes)
    {
        $find = SortLink::where('code', $Codes)->first();
   
        return redirect($find->Url);
    }
}

Step 6: Create View

resources/views/sortenLink.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to create url sortener in Laravel? - Laratuto.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 sortener in Laravel? - Laratuto.com</h1>
   
    <div class="card">
      <div class="card-header">
        <form method="POST" action="{{ route('generate.sorten.link.post') }}">
            @csrf
            <div class="input-group mb-3">
              <input type="text" name="link" class="form-control" placeholder="Enter URL" aria-describedby="basic-addon2">
              <div class="input-group-append">
                <button class="btn btn-success" type="submit">Generate Sorten Link</button>
              </div>
            </div>
        </form>
      </div>
      <div class="card-body">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Sort Link</th>
                        <th>Url</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($shortLinks as $row)
                        <tr>
                            <td>{{ $row->Id }}</td>
                            <td><a href="{{ route('sorten.link', $row->Codes) }}" target="_blank">{{ route('sorten.link', $row->Codes) }}</a></td>
                            <td>{{ $row->Url }}</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
      </div>
    </div>
   
</div>
    
</body>
</html>

Now we done…

php artisan serve

Now you can open url on your browser:

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

Read Also:

https://laratuto.com/how-to-get-last-insert-id-in-laravel/

35 thoughts on “How to create url shortener in Laravel 8?”

  1. Link exchange is nothing else except it is just placing the other person’s website link on your page at proper place and other person will also do same in support
    of you.

    Reply
  2. Thank you for another informative web site. Where
    else could I am getting that kind of info written in such an ideal way?
    I have a venture that I am just now operating on, and I’ve been at the look out
    for such info.

    Reply
  3. You would like to send millions , or hundreds of messages to Instagram users.
    Have a special offer that you would like to make available to an exclusive audience?

    GetBoost is pleased to offer the most advanced MASSDM service worldwide!

    Join thousands of customers who are generating tons of leads and sales for their clients by using
    GetBoost.

    * The cheapest prices
    * Fast delivery
    * Send up to one million messages every day!

    The promotion on Instagram with MASS DM is working!
    Visit https://bit.ly/massdm1 now and click on the bio
    link to order or more information.

    Secure payment options:
    Paypal Credit Card Crypto

    Reply
  4. We’ve all experienced software program issues, even from major corporations comparable to
    Microsoft, Google, or Apple. Because in my view, Elementor Pro will
    section out because of a few issues, and comparatively, GenerateBlocks is here to remain. All of my content on my site was created with GenerateBlocks
    Pro and Block Editor; consequently, my site velocity has soared
    and is now loading at 1.7 seconds. Boosting web page loading pace is one other advantage, particularly when you’ve a lightweight theme.
    How to install Elementor page builder domestically on your computer?
    PHP fatal error: namespace declaration statement has to be the very
    first assertion or after any declare call in the script:Should you receive this error, go to your FTP information, delete Elementor (or Elementor Pro if the
    error is linked to Elementor professional) and
    install the latest version of Elementor (or
    Elementor Pro). When you choose to edit a brand new web page with Elementor, the very first thing you will notice would
    be the including panel; you will be asked so as to add a brand new section or a template.
    Elementor has been in-built such a way that solely the scripts needed are loaded on a page by web
    page foundation. Select Elementor Pro Upload and activate it.
    So, Can you Get Elementor Pro Without spending a dime? You can save the new look to be a template on its own which you
    could reuse for one more web page or share with the general public.
    2. Give your web page a reputation and reserve it as a draft (you’ll publish it when it’s ready).
    The Elementor web page builder plugin will
    then install, and you’re free to start out utilizing it as soon as it does.

    Download the plugin file (.zip) through the button on this page.
    Elementor Pro Nulled is a WordPress web page builder that has no restrictions.
    How to put in Elementor on WordPress? If you use the page builder or are desirous about it, you’ll have come throughout these sorts of
    questions on forums and different dialogue areas dedicated to Elementor.
    10 million, because the quantity of websites on which Elementor can be lively,
    in accordance with the figures provided by the web page builder.
    Plus – $99 per 12 months (for three websites). However, every year
    10,000s of WordPress websites get hacked, and about 90% of all hacked websites are WordPress
    websites. Elementor is free, however the Pro version is available in three packages
    that provide the identical features however differ within the number of websites you
    can use it for. If you wish to have full control over your design, you don’t even have to use a template, you can build your web page from
    scratch. Elementor is among the quickest web page
    builders. Most page builders have a wide range of widgets, layouts.

    Beaver Builder, we’ve discovered that both page builder plugins supply unique and helpful features.
    Built with Elementor, Innomerce has Jet Plugins pack inside.
    If you are looking to start out adding extra
    features to Elementor, you’ve got three tiers that you can attempt.

    Elementor Pro Original License Key Cheap
    Elementor Pro Original License Key Free

    Reply
  5. I’ve been browsing online more than 3 hours today, yet I
    never found any interesting article like yours.

    It’s pretty worth enough for me. In my view,
    if all webmasters and bloggers made good content as you
    did, the internet will be much more useful than ever before.

    Reply
  6. You’ve made some really good points there. I checked on the internet for more information about the issue and found most individuals will go along with your views on this website.

    Reply
  7. I’m not that much of a internet reader to be honest but your
    blogs really nice, keep it up! I’ll go ahead and bookmark your website to come back down the road.
    Many thanks

    Reply
  8. Have you ever considered writing an ebook or guest authoring on other sites?

    I have a blog based upon on the same ideas you discuss and
    would love to have you share some stories/information. I know my
    readers would value your work. If you’re even remotely
    interested, feel free to shoot me an e mail.

    Reply
  9. That is really attention-grabbing, You’re an excessively professional blogger.
    I’ve joined your rss feed and look forward
    to in quest of more of your fantastic post. Additionally, I have shared your web site in my social networks

    Reply

Leave a Comment