KodeInfo | Learning resources for web and mobile development

Building A URL Shortener Website using Laravel 4 - Part 2

January 7th, 2015 15:10:00 by Imran Iqbal Comments(0) - Views(694)
Tags :

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.

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 

Kode Info

Author

  • Imran Iqbal
    Imran Iqbal

    Imran is a web developer and consultant from India. He is the founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.

Related

WHY USE A FRAMEWORK OVER PLAIN PHP

WHY USE A FRAMEWORK OVER PLAIN PHP
read more

GETTING STARTED WITH LARAVEL

GETTING STARTED WITH LARAVEL
read more

UNDERSTANDING LARAVEL STRUCTURE

UNDERSTANDING LARAVEL STRUCTURE
read more

UNDERSTANDING LARAVEL ROUTES

UNDERSTANDING LARAVEL ROUTES
read more

comments powered by Disqus