January 29, 2015 11:30 am

Building A URL Shortener Website using Laravel 4 – Part 2

This tutorial in continuation to the previous tutorial Building A URL Shortener Website using Laravel 4 – Part 1 where we saw how to start a web application using Laravel, database design, migrations, creating a view for user inputs and model to use Eloquent ORM feature of Laravel. In this tutorial we will see how we can validate the input submitted by the user, saving the data to the database, giving feedback to the user after submission and getting URL from database using shortened url.

Building A URL Shortener Website using Laravel 4 - Part 2

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

Saving data to the database

We will continue where we left in the previous post. Now we need to write a route that will have to listen to our post request. For this, we have to open routes.php file in app directory.

Now first we have to create a route to take care post form submit action in routes.php  file.

Route::post('/',function(){
 
    // post form submit code will come here
});

Now to retrieve the user input we have to use Input::post() method to get post form parameters.

Input::post('url');

Using the post action function that we have written above, we will be getting the user input. Now we have to validate the user input with the Laravel’s built in Validation class. This class helps us prevent invalid inputs from getting into our database.

We first has to define a $rules array to set the rules for each field. In our application, we want the url to have a valid URL format. Then we can run the form validation using the Validator::make() method and assign it to the $validation variable.

//We first define the Form validation rule(s)
$rules = array(
    'url' => 'required|url'
);
 
//Then we run the form validation
$validation = Validator::make(Input::all(),$rules);

The $validation variable holds information. Using $validation->fails() and $validation->passes() we can get to know whether validation was successful or not and also $validation holds a method messages(), which contains the information of a failed validation.

If the validation fails then we have to redirect the user back to the form with old input and also with validation messages.

if($validation->fails()) {
         
        return Redirect::to('/')
        ->withInput()
        ->withErrors($validation);
    }

If validation successful then we have to check whether url existing in our database or not using laravel Eloquent.

//Now let's check if we already have the url in our database. If so, we get the first result
$url = Url::where('url','=',Input::get('url'))->first();

If the url existing in our database then we have to send the shortened url to the user and needs to redirect the user back to the form with the database result.

if($url) {
    return Redirect::to('/')
    ->withInput()
    ->with('url',$url->hash);
    //Else we create a new unique URL
}

If the url doesn’t exist in our database then we have to create a random string as a new hash for this url and needs to save it in the database.

//First we create a new unique Hash
            do {
                $newHash = Str::random(6);
            }while(Url::where('hash','=',$newHash)->count() > 0);
         
            //Now we create a new database record
            Url::create(array(
            'url' => Input::get('url'),
            'hash' => $newHash
            ));

Once we save the hash value in the database we have to redirect the user with the shortened url to the form view.

//And then we return the new shortened URL info to our action
        return Redirect::to('/')
            ->withInput()
            ->with('url',$newHash);
        }

After these whole validation and saving the shortened url into database, our post form action routing code looks like below:

Route::post('/submit',function(){
 
    //We first define the Form validation rule(s)
    $rules = array(
        'url' => 'required|url'
    );
 
    //Then we run the form validation
    $validation = Validator::make(Input::all(),$rules);
 
    //If validation fails, we return to the main page with an error info
    if($validation->fails()) {
         
        return Redirect::to('/')
        ->withInput()
        ->withErrors($validation);
    } else {
         
        //Now let's check if we already have the url in our database. If so, we get the first result
        $url = Url::where('url','=',Input::get('url'))->first();
     
        //If we have the URL saved in our database already, we provide that information back to view.
        if($url) {
            return Redirect::to('/')
            ->withInput()
            ->with('url',$url->hash);
            //Else we create a new unique URL
        } else {
            //First we create a new unique Hash
            do {
                $newHash = Str::random(6);
            }while(Url::where('hash','=',$newHash)->count() > 0);
         
            //Now we create a new database record
            Url::create(array(
            'url' => Input::get('url'),
            'hash' => $newHash
            ));
         
        //And then we return the new shortened URL info to our action
        return Redirect::to('/')
            ->withInput()
            ->with('url',$newHash);
        }
    }
});

Getting individual URL from the database and redirecting

Now the final part of our application, we need to get hash part from the generated URL, and if there is a value, we need to redirect it to the URL which is stored in our database. To do this, add the following code at the end of our routes.php file under app folder.

Route::get('{hash}',function($hash) {
 
    //First we check if the hash is from a URL from our database
 
    $link = Link::where('hash','=',$hash)->first();
 
    //If found, we redirect to the URL
 
    if($link) {
        return Redirect::to($link->url);
 
        //If not found, we redirect to index page with error message
 
    } else {
 
    return Redirect::to('/')
        ->with('message','Invalid Link');
    }
})->where('hash', '[0-9a-zA-Z]{6}');

In the above code we just written a route code with a parameter called hash and with the where() method we define how the name parameter will be. The first parameter is the name of the variable and the second parameter is a regular expression that will filter the parameter. In our case the regular expression filters an exact alphanumeric string that is six characters long. This way we can filter our URLs and secure them from start and we won’t have to check if the url parameter has something we don’t want.

Let’s go throught the code line by line to know what we are doing. First we are checking whether the hash is from an URL in our database or not.

//First we check if the hash is from a URL from our database
$link = Link::where('hash','=',$hash)->first();

If there is a result, we redirect the page to the url column of our database, which has the link to which the user should be redirected.

if($link) {
    return Redirect::to($link->url);
    //If not found, we redirect to index page with error message
}

If there is no result, we redirect the user back to our index page using $message variable, which holds the value Invalid URL.

else {
    return Redirect::to('/')
        ->with('message','Invalid Link');
    }

We can show this Invalid URL message in the form by using the following code.

@if(Session::has('message'))
<h3 class="error"> {{ Session::get('message') }} </h3>
@endif

In this application tutorial series, we have covered the basic usage of laravel’s routes, models, artisan commands, and database drivers by making a simple URL shortener website. After this series of tutorials we can create database tables with migrations, write simple forms with the laravel form builder class, validate these forms with the validation class, and process these forms and insert new data to the tables with the fluent query builder or eloquent ORM.

We will come up with another example where we are going to use extensively these features.

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 2”

  1. yacer1 says:

    thanks men ..<3

  2. Ext Concepts says:

    This is a very powerful tutorial, it is what i have been looking for.Pls send the link to download the source code.
    Thank you

  3. Danilo Polani says:

    First part: Awesome! This second.. You don’t write where to put the code, for new users is not simple. Please update.

  4. Danilo Polani says:

    Line 5 of the route with hash is wrong. It’s Url::where, not Link::where.

Leave a Reply

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