January 28, 2015 11:07 am

Building A URL Shortener Website using Laravel 4 – Part 1

Todays we are going to start a series of tutorials about building a URL shortener website using Laravel 4 framework. I hope this tutorial helps to understand laravel features through practical example. We will see how to build a URL Shortener website with Laravel 4 framework. This whole tutorial is going to be divided into sub topics.

Building A URL Shortener Website using Laravel 4 - Part 1

See Part 2: Building A URL Shortener Website using Laravel 4 – Part 2

Topics are.

  • Laravel project configuration.
  • Creating a database and migrating our URL Shortener’s table.
  • Creating our form.
  • Creating our link model
  • Saving data to database
  • Getting individual URL from the database and redirecting.

Project Configuration

Let’s setup the project folder first before we start building website. First we have to self update our composer to make sure it doesn’t give any problems in middle using PHP.

composer self-update

In the next step we have to create project folder using composer with following command.

composer create laravel/laravel urlshortener

laravel home page

Creating a database and migrating our URL shortener table

Any time before creating an application first thing we have to do is building our database schema design. For that we will use laravel migrations. Migrations are like version control for our application’s database. They permit a team to modify database schema, and provide up-to-date information on the current schema state. We have to follow below steps to create and migrate our URL shortener database.

Before creating a migration first of all, we have to create a database, and define the connection information to laravel. To do this, we open app/config/database.php  and then fill the required credentials. Laravel supports multiple databases like MySQL, SQLite, PostgreSQL, and SQLSRV ( Microsoft SQL Server) by default , we can change in between these different database drives seamlessly without having lot of changes.

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 urlshortener

The previous SQL query will generate a new MySQL database named urlshortener for us. After this we will define database credentials in app/config/database.php file.

'mysql' => array(
			'driver'    => 'mysql',
			'host'      => 'localhost',
			'database'  => 'urlshortener',
			'username'  => 'username',
			'password'  => 'password',
			'charset'   => 'utf8',
			'collation' => 'utf8_unicode_ci',
			'prefix'    => '',
		),

We can see default key defines what database driver to be used and each database driver key holds individual credentials. We will be using MySQL for this application.

We have completed database configuration. Now, we will be using the Artisan CLI to create migrations. Artisan is a command line interface specially made for laravel. We will be using migrate:make command to create a migration on Artisan.

php artisan migrate:make create_urls_table --table=urls --create

This command has two parts:

  • The first is migrate:make create_urls_table. This part of the command creates a migration file which is named something like 2015_01_06_151323_create_urls_table.php.
  • The second part of the command is –table=urls –create. This part of the command creates a table with name urls on the database server.

When we run the previous command, it creates our migration. We can access the migration file under app/database/migrations, having the following code:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUrlsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('urls', function(Blueprint $table)
		{
			//
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('urls', function(Blueprint $table)
		{
			//
		});
	}

}

Let’s inspect the sample migration file. There are two public functions which are declared as up() and down(). When we execute the following migrate command, the contents of the up() function will be executed.

php artisan migrate

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

We can also roll back our 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

Now , let’s add our fields which are required for this application. We have 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 migration after adding our two fields looks like the following.

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUrlsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('urls', function(Blueprint $table)
		{
			$table->increments('id');
			$table->text('url');
			$table->string('hash', 400);			
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('urls');
	}

}

Creating our form

Now let’s create our view which will contain a form to take input url from the users to shorten. For this we are going to benefit from Laravel 4 built in template engined called Blade. We are going to create a new file in app/views directory and naming as form.blade.php file. We will be using Twitter Bootstrap framework for building this form.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>URL Shortener</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

  </head>
  <body>
    
    <div class="container">
		<div class="row clearfix">
			<div class="col-md-6 col-md-offset-3">
				<h2 style="text-align:center;"> URL Shortener </h2>

				{{ Form::open(array('url' => '/', 'method' => 'post')) }}

				<div class="form-group">
					{{
						Form::text('url', Input::old('url'),array('class' => 'form-control', 'placeholder' => 'Insert your Urls and press enter', 'required' => 'required'))
					}}
				</div>

				{{ Form::close() }}

			</div>
		</div>
	</div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
  </body>
</html>

This code will produce a form that looks like the following screenshot:

URL form

We have used the Laravel’s built in Form class to generate a form, and we have used the old() method of the Input library.

Form::open() creates a <form> opening tag with parameters of post url routing and what type of method we are going to use for this form.

Form::text() creates a <input> tag with type as text. We can pass name of the text input, class and other parameters to this method.

Form::close() closes the <form> tag.

Creating our link model

To benefit from Laravel’s ORM class called Eloquent, we need to define a model. let’s create a file name called url.php in app/models directory.

<?php

class url extends Eloquent
{
	protected $table 	= 'urls';
	protected $fillable = array('url','hash');
	public $timestmps 	= false; 
}

The variable $table is used to define the table name for the model, but it’s not compulsory. Even if we don’t define this variable, it would use the plural form of the model names as a database table name.

The protected $fillable variables defines what columns can be created and updated. Laravel 4 blocks the mass assignment of the values of all the columns with Eloquent  by default.

The public $timestamps variable checks whether the model should try setting the timestamps created_at and updated_at by default.

Now we have to route the user to the form to submit url to shortened for that we can do it on routes.php directly or through controllers defined in routes.php file. Let’s write some routing code in routes.php file.

Route::get('/', function()
{
	return View::make('form');
});

Till now we setup the database configuration, written migrations to create tables, created a form to submit urls for shortening and also written a routing to route users to form.

In the next tutorial we will see how to submit the form, saving the data into database and form validation with url shortening.

Thanks

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

4 responses to “Building A URL Shortener Website using Laravel 4 – Part 1”

  1. Abimbola CodingPope Popoola says:

    This is awesome! Thumbs up Huzoor.. Waiting for the next part.

  2. Chris says:

    This whole site is amazing. You have taught me so much about PHP. Really appreciate it

  3. Danilo Polani says:

    Line 7 of the Url defining: timestamps is written wrong

Leave a Reply

Your email address will not be published. Required fields are marked *