January 12, 2015 7:40 am

Laravel 4 Basics Part 2: Refactoring and Finishing the Basic Application

In this part, we are going to finish the Basic Application started in Part 1 and give you a little more knowledge on controllers, form builder, url, input and redirect helpers in Laravel and we are going to provide a sample of using layouts/templates in Laravel. Also, we are going to show some Bootstrap classes instead of inline styles.

laravel 4 Basics part 2

[wpdm_file id=123]
<?php
Route::get('/', function()
{
	return Redirect::to('guess');
});
Route::get("guess", array('as'=>'guess', 'uses'=>'GuessController@getGuess'));
?>

Firstly, we set the request for the index of the application (our public folder) will redirect to the guess route. This is possible because when defining the ‘guess’ route we provide an array of options and give a name to the route (‘as’ => ‘guess’).

In our guess route we set the GuessController.php as responsible for processing the request (which would be located in app/controllers) and declare that the getGuess function in that controller would handle the request (It could be explained as ‘uses’ => ‘controller@functionName’).
Now, our routes.php will not become massive if we had a lot of request URLs to catch and we have a named route.

See also: Laravel 4 Basics Part 1

Each controller has to be a class that inherits the BaseController. Therefore, we use :

<?php
class GuessControllerextendsBaseController {} in GuessController.php

	publicfunctiongetGuess() {
		if (Input::has("numbers")) {
			$numbers= Input::get("numbers");
			//Generate a random number between 0 and 20
			$luckyNumber=mt_rand(0,20);
			//Create an array with numbers
			$numbers=explode(",", $numbers );
			if (count($numbers) >5) {
				// Send to the view only the first 5 numbers
				$numbers=array_slice($numbers, 0, 5);
		}
			return View::make('layouts.main')->withPage("guess")->withNumbers($numbers)->with("lucky", $luckyNumber);

		
		}
		else
			return View::make("layouts.main")->withPage("home");
		
		
	}
?>

Then, we create our function getGuess().

You can see some changes. Now, we are using GET to send the numbers from the user to the view. Therefore, we use Input::has(‘name attribute of form’s element’) to check if there is an input called numbers and if there is we store it in a variable by using Input::get(“numbers”);

If the request method was POST we could have used Input::post(“numbers”);

Alternatively, we could have used Input::any(“numbers”);

A small note is that you can send all user inputs to a view with the withInput() method. For example,

View::make("layouts.main")->withPage("search")->withInput();

Another note is that Laravelallows .(dot) as a directory separator. Therefore,return View::make(“layouts.main”) is the same as return View::make(“layouts/main”) (layouts is a directory within the Views folder)

We see that now we use one view for all our requests (the template) and pass it a $page variable that tells which is the view of the page that is requested so it can include it.

Laravel Books:

Next, we create a view called home.blade.php and use Laravel’s Form Builder.

<h1 class="alert alert-warning text-center"> Guess the number. You can enter up to 5 numbers in a comma-separated list</h1>

<div id="guess-container" class="text-center">

{{Form::open(array('method'=>'get', 'route'=>'guess', 'class'=>'form-horizontal')) }}	
{{Form::label('numbers', 'Enter your guess:') }}
{{Form::text('numbers', '10', array('class'=>'form-control', 'pattern'=>"^([\d]{1,2},?){1,5}$")) }}
{{Form::submit('I am feeling lucky', array("class"=>'btnbtn-default'))}}
{{Form::close() }}
</div>

We start a form with Form::open($settingsArray) and close it with Form::close();
Inside the form, we create a label, the first argument to the static method is the for=”” name of the label and the second is the text of the label.
Next, we create an <input type=”text”> with the text() static method and pass as a first argument again the name, a default value and an array of options. The options could include all kinds of attributes. For example, here we have included as a HTML5 attribute called pattern which takes as a value a regular expression – “^([\d]{1,2},?){1,5}$”

As you can see this regular expression allows only inputs starting with 1 or 2 digits optionally followed by a comma with more digits and commas up to 5 times and ends there.
We add a submit button with Bootstrap classes in the options array and close the form.

Figure 1: You can insert any attribute in the options array of the Form Builder

Our main template looks like this:

<!DOCTYPE html>
<html lang="en">
	<head>
	<meta charset="UTF-8">
	<title>Guess the number</title>
	<linkrel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
	<style>
		.no-bg {
			background: none;
			border: none;
		}
	</style>

	</head>
	<body>
		<ul class="navnav-pills" style="font-size: 1.2em;">
			<li><a href="https://www.phpgang.com" target="_blank">PHPGang</a></li>
			<li><a href="<?php echo URL::to('guess') ?>">Guess</a></li>
		</ul>
		<div class="container">
			<div class="row">
				<div class="col-lg-12">
					<div class="well well-md" id="content">
					
						
						@include($page);
					
					
					</div>
					<div class="alert text-center"><span class="glyphiconglyphicon-heart"></span>&nbsp;Laravel Basics, Part II</div>
					</div>
			</div>
		</div>
	</body>
</html>

Worth mentioning is the @include($page) function call. Blade uses @include similar to native PHP’s include and we pass it the page variable given to us by the controller to populate the ‘content’ div.

Another new thing is

<li><a href="<?php echo URL::to('guess') ?>">Guess</a></li>

URL is a Laravel helper class with static methods. What we did here is pass it the name that we gave to our route in routes.php and it automatically built a link (URL) to that route.

We are going to use that same template for the more meaningful applications that we are going to create in the next Laravel Basics articles, just pass it a different $page variable and add the application to the menu in the top of the page.

Almost nothing changes in our guess.blade.php View except some cosmetic changes (Mostly adding Bootstrap classes that you can examine at: http://getbootstrap.com/components/ )

<div class="text-center">

		<h1> Did you guess the lucky number?</h1>
		<p>The actual lucky number is between 0and20</p>
		
			@foreach ($numbersas$number)
				@if ($number==$lucky) 
				<h1 class="alert alert-success no-bg"><span class="glyphiconglyphicon-ok"></span> You said {{{ $number }}}. You guessed the lucky number! Jackpot!</h1>
				@else
					<h1 class="alert alert-danger no-bg"><span class="glyphiconglyphicon-remove"></span> You said {{{ $number }}}. You did not manage to guess the lucky number.</h1>
				@endif;

			@endforeach

			<h1 class='alert alert-info no-bg'><span class='glyphiconglyphicon-info-sign'></span>The lucky number was {{ $lucky }} </h1>
		
	
	</div>

The Bootstrap stylization above results in the following page:

Figure 2 Guess the lucky number Laravel basics

That’s all for Laravel first series our team is working on it and very soon you will see more articles on Laravel.

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories:

One response to “Laravel 4 Basics Part 2: Refactoring and Finishing the Basic Application”

  1. Sameer says:

    Nice work I love Laravel

Leave a Reply

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