Build your own URL shortener using Laravel

Build your own URL shortener using Laravel

In this article, you'll learn how to generate short url in laravel application.

Sometime we need to make shorten url string instead of long 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 own script function for generator short link in Laravel.

If you are working with SMS or some where share with limited character and at that time if you need to share any url or link then you must have to generate shortener url. In your project it's need many times then you must have to implement module that can help to generate url shortener with your website domain.

You need to just follow step by step this tutorial, you will get very simple module for generate short link in Laravel 5. I will also give you free download whole script.

Step 1: Install Laravel 5

In this step, if you haven't Laravel 5 application setup then we have to get fresh Laravel 5 application. So run bellow command and get 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 for create short link. so we have to create migration for "short_links" table using Laravel 5.8 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 following path "database/migrations" and you have to put bellow code in your migration file for create short_links table.

<?php
  
use 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 following command:

php artisan migrate

Step 3: Create Model

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

php artisan make:model ShortLink

app/ShortLink.php

<?php
   
namespace 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 is step we need to create route for layout file and another one for store data. so open your routes/web.php file and add following route.

routes/web.php

Route::get('generate-shorten-link', '[email protected]');
Route::post('generate-shorten-link', '[email protected]')->name('generate.shorten.link.post');
   
Route::get('{code}', '[email protected]')->name('shorten.link');

Step 5: Create Controller

In this point, now we should create new controller as ShortLinkController. this controller will manage layout and store data to database, so put bellow content in controller file:

app/Http/Controllers/ShortLinkController.php

<?php
  
namespace 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 View

In Last step, let's create shortenLink.blade.php(resources/views/shortenLink.blade.php) for layout and we will write design code here and put 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 bellow command ro quick run:

php artisan serve

Now you can open bellow url on your browser:

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

You can download whole code from here

Clear Cache in Laravel 6.8 App using Artisan Command Interface (CLI)

Clear Cache in Laravel 6.8 App using Artisan Command Interface (CLI)

In Laravel 6 tutorial, we learn how to use PHP artisan command interface (CLI) to clear the cache from Laravel 6.8 application. How To Clear Cache in Laravel 6.8 Application using Artisan Command Line Interface (CLI)? How to clear route cache using php artisan command? How to easily clear cache in Laravel application? How to clear config cache in PHP Laravel via artisan command? How to clear Laravel view cache? How to Reoptimized class in Laravel via artisan CLI?

Today in this tutorial, we are going to learn how to clear route cache, laravel application cache, config cache, view cache and reoptimized class in a Laravel 6.8 application using artisan command-line interface.

I’m pretty sure many of you may have found yourself gotten into the situation where you do not see changes in the view after making the changes in the app.

Laravel application serves the cached data so caching problem occurs due to the robust cache mechanism of Laravel.

But, if you are still facing this issue, then you do not have to worry further. Let me do the honour of introducing you some of the best artisan commands to remove the cache from your Laravel app via PHP artisan command line interface.

Artisan is the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application.

Table of Contents

  • Clear Route Cache in Laravel
  • Clear Laravel Application Cache
  • Clear Config Cache via PHP Artisan
  • Clear Laravel View Cache
  • Reoptimized Class
Clear Route Cache in Laravel

Laravel caching system also takes routes in consideration, to remove route cache in Laravel use the given below command:

php artisan route:cache
Clear Application Cache in Laravel

Run the following command to clear application cache:

php artisan cache:clear
Clear Config Cache in Laravel

Run the following command to clear config cache:

php artisan config:cache
Clear View Cache in Laravel

Run the following command to clean your view cache:

php artisan view:clear
Reoptimize Class

Run the below command to reoptimize the class loader:

php artisan optimize

Conclusion

We have completed this Laravel 6 tutorial, In this tutorial we learned how to use php artisan command to clear the cache from your Laravel application. We have answered the following questions in this article.

  • How to clear route cache using php artisan command?
  • How to easily clear cache in Laravel application?
  • How to clear config cache in PHP Laravel via artisan command?
  • How to clear Laravel view cache?
  • How to Reoptimized class in Laravel via artisan CLI?

Now, it’s your time to let me know what do you think about this laravel 6 article. Go forth and try these super awesome artisan commands and let me know how these commands are helping you.

Get Weather Data with Laravel Weather

Get Weather Data with Laravel Weather

Get Weather Data with Laravel Weather. Laravel Weather is a good package which we can use to get weather data. It's a wrapper around Open Weather Map API (Current weather). A wrapper around Open Weather Map API (Current weather)

🌤️ A wrapper around Open Weather Map API (Current weather)

Installation

You can install the package via composer:

source-shell
composer require gnahotelsolutions/laravel-weather
Usage
text-html-php
$weather = new Weather();

// Checking weather by city name
$currentWeatherInGirona = $weather->get('girona,es');

// You can use the city id, this will get you unambiguous results
$currentWeatherInGirona = $weather->find('3121456');

Units

By default the package uses metric for Celsius temperature results, this can be modified using the configuration file or on the fly:

text-html-php
$weather = new Weather();

$currentWeatherInGirona = $weather->inUnits('imperial')->get('girona,es');

Language

By default the package uses es for the description translation, this can be modified using the configuration file or on the fly:

text-html-php
$weather = new Weather();

$currentWeatherInGirona = $weather->inLanguage('en')->get('girona');

Guzzle Client Instance

If you need to use another instance of Guzzle, to modify headers for example:

text-html-php
$weather = new Weather();

$guzzle = $this->getSpecialGuzzleClient();

$currentWeatherInGirona = $weather->using($guzzle)->get('girona');

Testing

source-shell
composer test

Laravel Sweet Alert | How to use the SweetAlert package in Laravel PHP

Laravel Sweet Alert | How to use the SweetAlert package in Laravel PHP

Sweet Alert is a laravel wrapper around #sweetalert javascript library for showing alert or notification message. This is a great package created by rashid, and this laravel package is very famous because it has tonnes of features you can choose from.

Sweet Alert is a laravel wrapper around #sweetalert javascript library for showing alert or notification message.

This is a great package created by rashid, and this laravel package is very famous because it has tonnes of features you can choose from.