Build a Link Shortner App Using Laravel

In thisTutorial , Build a Link Shortner App Using Laravel with the basics of Laravel framework.

Creating a database and migrating our URL shortener’s table

Migrations are like version control for your application’s database. They permit a team (or yourself) to modify the database schema, and provide up-to-date information on the current schema state. To create and migrate your URL Shortener’s database, perform the following steps:

  1. First of all, we have to create a database, and define the connection information to Laravel. To do this, we open the database.php file under app/config, and then fill the required credentials. Laravel supports MySQL, SQLite, PostgreSQL, and SQLSRV (Microsoft SQL Server) by default. For this tutorial, we will be using MySQL.
  2. We will have to create a MySQL database. To do this, open your MySQL console (or phpMyAdmin), and write down the following query:
    CREATE DATABASE urls
    
  3. The previous command will generate a new MySQL database named urls for us. After having successfully generated the database, we will be defining the database credentials. To do this, open your database.php file under app/config. In that file, you will see multiple arrays being returned with database definitions.
  4. The default key defines what database driver to be used, and each database driver key holds individual credentials. We just need to fill the one that we will be using. In our case, I’ve made sure that the default key’s value is mysql. To set the connection credentials, we will be filling the value of the mysql key with our database name, username, and password. In our case, since we have adatabase named urls, with the username as root and without a password, our mysqlconnection settings in the database.php file will be as follows:
    'mysql' => array(
      'driver' => 'mysql',
      'host' => 'localhost',
      'database' => 'database',
      'username' => 'root',
      'password' => '',
      'charset' => 'utf8',
      'collation' => 'utf8_unicode_ci',
      'prefix' => '',
    ),

    Now, we will be using the Artisan CLI to create migrations. Artisan is a command-line interface specially made for Laravel. It provides numerous helpful commands to help us in development. We’ll be using the following migrate:make command to create a migration on Artisan:

  5. php artisan migrate:make create_links_table --table=links --create
    

    The command has two parts:

    • The first is migrate:make create_links_table. This part of the command creates a migration file which is named something like2013_05_01_194506_create_links_table.php. We’ll examine the file further.
    • The second part of the command is --table=links --create.
      • The --table=links option points to the database name.
      • The --create option is for creating the table on the database server to which we’ve given the --table=links option.
    • As you can see, when you run the previous command, it will create both the migrations table and our migration. You can access the migration file underapp/database/migrations, having the following code:
      <?php
      use Illuminate\Database\Schema\Blueprint;
      use Illuminate\Database\Migrations\Migration;
      class CreateLinksTable extends Migration {
        /**
        * Run the migrations.
        *
        * @return void
        */
        public function up()
        {
          Schema::create('links', function(Blueprint $table)
          {
            $table->increments('id');
          });
        }
        /**
        * Reverse the migrations.
        *
        * @return void
        */
        public function down()
        {
          Schema::drop('links');
        }
      }
    • Let’s inspect the sample migration file. There are two public functions which are declared as up()and down(). When you execute the following migrate command, the contents of the up()function will be executed:
      php artsian migrate
      

      This command will execute all of the migrations and create the links table in our case.

      Note

      If you receive a class not found error when running the migration file, try running thecomposer update command.

    • We can also roll back to the last migration, like it was never executed in the first place. We can do this by using the following command:
      php artisan migrate:rollback
      
    • In some cases, we may also want to roll back all migrations we have created. This can be done with the following command:
      php artisan migrate:reset
      
    • While in the development stages, we may forget to add/remove some fields, or even forget to create some tables, and we may want to roll back everything and remigrate them all. This can be done using the following command:
      php artisan migrate:refresh
      
    • Now, let’s add our fields. We’ve created two additional fields called url and hash. The url field will hold the actual URL, to which the URL present in the hash field will be redirected. The hash field will hold the shortened version of the URL that is present in the url field. The final content of the migration file is as shown in the following code:
      <?php
      use Illuminate\Database\Migrations\Migration;
      class CreateLinksTable extends Migration {
        /**
        * Run the migrations.
        *
        * @return void
        */
        public function up()
        {
          Schema::create('links', function(Blueprint $table)
          {
            $table->increments('id');
            $table->text('url');
            $table->string('hash',400);
          });
        }
        /**
        * Reverse the migrations.
        *
        * @return void
        */
        public function down()
        {
          Schema::drop('links');
        }
      }

       

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

2 Comments
by Deven Rathore
5 min read

Pin It on Pinterest

Shares