<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dayle Rees</title>
	<atom:link href="http://daylerees.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://daylerees.com</link>
	<description>Tools, Frameworks, Snippets, and other time saving goodies…</description>
	<lastBuildDate>Fri, 18 May 2012 16:56:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Trick: Validation within Models</title>
		<link>http://daylerees.com/2012/05/18/trick-validation-within-models/</link>
		<comments>http://daylerees.com/2012/05/18/trick-validation-within-models/#comments</comments>
		<pubDate>Fri, 18 May 2012 16:56:25 +0000</pubDate>
		<dc:creator>Dayle</dc:creator>
				<category><![CDATA[Laravel Tricks]]></category>

		<guid isPermaLink="false">http://daylerees.com/?p=266</guid>
		<description><![CDATA[Often when dealing with Eloquent models you will fall into the pattern of retrieving data from the user, validating it, filling the model and saving it. This is perfectly fine, but can lead to a large amount of validation code within your routes and controllers. Let&#8217;s have a look at how we can shift some [...]]]></description>
			<content:encoded><![CDATA[<p>Often when dealing with Eloquent models you will fall into the pattern of retrieving data from the user, validating it, filling the model and saving it.</p>
<p>This is perfectly fine, but can lead to a large amount of validation code within your routes and controllers. Let&#8217;s have a look at how we can shift some of the validation logic into our models instead and clean up our routing. First we will need our Eloquent model.</p>
<pre><code>class Ball extends Eloquent
{

}
</code></pre>
<p>Great! That&#8217;s all we need, now lets add a new private property to the model called rules. This will store our validation rules array in the usual format.</p>
<pre><code>class Ball extends Eloquent
{
    private $rules = array(
        'color' =&gt; 'required|alpha|min:3',
        'size'  =&gt; 'required',
        // .. more rules here ..
    );
}
</code></pre>
<p>Great! Now our rules are attached to our model, this means that we won&#8217;t have to recreate the validation array each time we create a new model instance. Now we need a way of using these rules, I like to create a public <code>validate()</code> method, let&#8217;s take a look..</p>
<pre><code>class Ball extends Eloquent
{
    private $rules = array(
        'color' =&gt; 'required|alpha|min:3',
        'size'  =&gt; 'required',
        // .. more rules here ..
    );

    public function validate($data)
    {
        // make a new validator object
        $v = Validator::make($data, $this-&gt;rules);
        // return the result
        return $v-&gt;passes();
    }
}
</code></pre>
<p>Great! Now we can validate our models using the following syntax.</p>
<pre><code>// get the POST data
$new = Input::all();

// create a new model instance
$b = new Ball();

// attempt validation
if ($b-&gt;validate($new))
{
    // success code
}
else
{
    // failure
}
</code></pre>
<p>That&#8217;s a lot more compact, but we are missing something important. What about our validation errors? We will need those for our forms. Let&#8217;s create a new private attribute to store them.</p>
<pre><code>class Ball extends Eloquent
{
    private $rules = array(
        'color' =&gt; 'required|alpha|min:3',
        'size'  =&gt; 'required',
        // .. more rules here ..
    );

    private $errors;

    public function validate($data)
    {
        // make a new validator object
        $v = Validator::make($data, $this-&gt;rules);

        // check for failure
        if ($v-&gt;fails())
        {
            // set errors and return false
            $this-&gt;errors = $v-&gt;errors;
            return false;
        }

        // validation pass
        return true;
    }
}
</code></pre>
<p>Now we need a method to be able to retrieve the errors object.</p>
<pre><code>class Ball extends Eloquent
{
    private $rules = array(
        'color' =&gt; 'required|alpha|min:3',
        'size'  =&gt; 'required',
        // .. more rules here ..
    );

    private $errors;

    public function validate($data)
    {
        // make a new validator object
        $v = Validator::make($data, $this-&gt;rules);

        // check for failure
        if ($v-&gt;fails())
        {
            // set errors and return false
            $this-&gt;errors = $v-&gt;errors;
            return false;
        }

        // validation pass
        return true;
    }

    public function errors()
    {
        return $this-&gt;errors;
    }
}
</code></pre>
<p>Great! Let&#8217;s take a look at it in action.</p>
<pre><code>// get the POST data
$new = Input::all();

// create a new model instance
$b = new Ball();

// attempt validation
if ($b-&gt;validate($new))
{
    // success code
}
else
{
    // failure, get errors
    $errors = $b-&gt;errors();
}
</code></pre>
<p>We now have a working validation model, but to use this same system across many models we would have to replicate the code across the other classes..</p>
<blockquote>
<p>Dayle, surely there&#8217;s a better way?</p>
</blockquote>
<p>Do not fear! There is always a better way! Let&#8217;s create a new base model with the code that we have already used. I like to call mine <code>Elegant</code>.</p>
<pre><code>class Elegant extends Eloquent
{
    protected $rules = array();

    protected $errors;

    public function validate($data)
    {
        // make a new validator object
        $v = Validator::make($data, $this-&gt;rules);

        // check for failure
        if ($v-&gt;fails())
        {
            // set errors and return false
            $this-&gt;errors = $v-&gt;errors;
            return false;
        }

        // validation pass
        return true;
    }

    public function errors()
    {
        return $this-&gt;errors;
    }
}
</code></pre>
<p>Now we can have our models extend the base model <code>Elegant</code> instead of <code>Eloquent</code>, define a <code>$rules</code> array, and have access to all the validation features we had before..</p>
<pre><code>class Ball extends Eloquent
{
    protected $rules = array(
        'color' =&gt; 'required|alpha|min:3',
        'size'  =&gt; 'required',
        // .. more rules here ..
    );
}
</code></pre>
<p>That&#8217;s all for now! Enjoy using your validation friendly Elegant models!</p>
]]></content:encoded>
			<wfw:commentRss>http://daylerees.com/2012/05/18/trick-validation-within-models/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Laravel 3.2: The future is bright..</title>
		<link>http://daylerees.com/2012/05/02/laravel-3-2-the-future-is-bright/</link>
		<comments>http://daylerees.com/2012/05/02/laravel-3-2-the-future-is-bright/#comments</comments>
		<pubDate>Wed, 02 May 2012 17:04:14 +0000</pubDate>
		<dc:creator>Dayle</dc:creator>
				<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://daylerees.com/?p=255</guid>
		<description><![CDATA[With Laravel 3.2 just around the corner, I thought I would take some time out from my usual tutorials and show you all some of the new features that will land with the next version of Laravel. I&#8217;m a pretty modest guy, so let&#8217;s start with the features that I helped with first, me me [...]]]></description>
			<content:encoded><![CDATA[<p>With Laravel 3.2 just around the corner, I thought I would take some time out from my usual tutorials and show you all some of the new features that will land with the next version of Laravel. I&#8217;m a pretty modest guy, so let&#8217;s start with the features that I helped with first, me me me, me me ME me me me..</p>
<h2>Offline Docs</h2>
<p>It feels like a year since Taylor and I finished working on this, and I&#8217;m excited to hear what people have to say about it. We have had a lot of requests from the community for a method of taking the documentation with them. Apparently our coders are so relaxed and hip that they live jet set lifestyles, they need to be able to access the documentation on a plane, a jet ski, or the back of a giraffe. Your wish is our command, behold the offline docs.</p>
<p>Taylor had already setup most of the markdown processing when he approached me hoping for a simple modification to the welcome page to be able to view the docs, but we decided to take this a step further. We have since created all new welcome pages, error pages, and full documentation templates, all very clean and crisp and very easy to read on the move. Taylor let me have my wicked way with the design (should he be trusting a developer with design tasks? <img src='http://daylerees.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  and we are both pleased with the results. Let&#8217;s hope you are too! Here&#8217;s a quick preview for those who are too lazy to download the develop.</p>
<p><a href="http://daylerees.com/wp-content/uploads/2012/05/Laravel_-A-Framework-For-Web-Artisans-1.jpg"><img class="aligncenter size-medium wp-image-258" title="Laravel_ A Framework For Web Artisans-1" src="http://daylerees.com/wp-content/uploads/2012/05/Laravel_-A-Framework-For-Web-Artisans-1-300x194.jpg" alt="" width="300" height="194" /></a></p>
<h2>The Profiler</h2>
<p>Shortly after the release of Laravel 3.1, I created a little bundle that despite my shoddy javascript received a great deal of popularity, Anbu.</p>
<p>Anbu is a little toolbar that sits at the bottom of your views and reports useful information such as log entries, SQL queries performed, and other neat stuff. I added a few snazzy javascript animations and ended up with a useful but pretty front-end profiler. Taylor saw the profiler a short while later and seemed to fall in love with it (people please, look at the terrible JS!) and asked if it could be included into the core. Of course it can!</p>
<p>I integrated Anbu with the core, and added a little bit of extra branding to make it more Laravelsexy (it&#8217;s a word) and Taylor renamed the package to Profiler. As of Laravel 3.2 you can enable profiler in the configs, and debug til you are as happy as a red panda. Enjoy!</p>
<p><a href="http://daylerees.com/wp-content/uploads/2012/05/Laravel_-A-Framework-For-Web-Artisans-2.jpg"><img class="aligncenter size-medium wp-image-260" title="Laravel_ A Framework For Web Artisans-2" src="http://daylerees.com/wp-content/uploads/2012/05/Laravel_-A-Framework-For-Web-Artisans-2-300x26.jpg" alt="" width="300" height="26" /></a></p>
<h2>Blade</h2>
<p>I was using blade to write some front end forms when I thought..</p>
<blockquote><p>Wouldn&#8217;t it be cool to be able to add comments to blade templates, to comment on the visual aspects of the application, without them being rendered at runtime.</p></blockquote>
<p>After much debate about whether it was a justifyable feature, and the format of the comments themselves, meet the new blade comments :</p>
<pre><code>{{-- a simple multiline comment --}}

{{-- a single line comment
</code></pre>
<p>I hope you find them as useful as I hoped they would be!</p>
<p>Blade also has a new <code>@unless</code> which acts as a simple &#8216;IF NOT&#8217;.</p>
<pre><code>@unless(3==3)
    &lt;p&gt;THREE MUST BE THREE&lt;/p&gt;
@endunless
</code></pre>
<p>Enjoy!</p>
<h2>to_array()</h2>
<p>or not to_array.. that is the question. Eloquent objects now have a <code>to_array()</code> method to return the object represented as a key-value array, simple!</p>
<h2>Authentication</h2>
<p>The Authentication system in Laravel is pretty neat, and with the addition of the config closures it became more configurable. Taylor has taken this a step further with the inclusion of Authentication drivers, allowing you to create a simple class to handle basic authentication methods, with the possibility of tieng the Authentication procedure to a data source of your choice.</p>
<p>Naturally Taylor has included Eloquent and Fluent drivers with 3.2 to provide some familiar defaults.</p>
<h2>Input::json()</h2>
<p>Now some methods to help those who are building API&#8217;s on top of Laravel. The Input::json() method allows you to retrieve the JSON payload of the Input class as an array, very handy for backbone and other JS FW&#8217;s!</p>
<p>You can now use Response::json() to output a JSON response from a PHP array, or Response::eloquent() to output an Eloquent object as JSON, super handy!</p>
<p>Well those are a few of my favorite features! The <a href="https://github.com/laravel/laravel/blob/develop/laravel/documentation/changes.md#3.2" target="_blank">complete list of features can be found here</a>. Thanks to everyone who has contributed to the project.</p>
<p>I would also like to say hi (wave) to our amazing Laravel Community members, come and join us in #laravel on freenode if you would like a chat!</p>
]]></content:encoded>
			<wfw:commentRss>http://daylerees.com/2012/05/02/laravel-3-2-the-future-is-bright/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Laravel: Validation</title>
		<link>http://daylerees.com/2012/04/30/laravel-validation/</link>
		<comments>http://daylerees.com/2012/04/30/laravel-validation/#comments</comments>
		<pubDate>Mon, 30 Apr 2012 20:30:12 +0000</pubDate>
		<dc:creator>Dayle</dc:creator>
				<category><![CDATA[Laravel Tutorials]]></category>

		<guid isPermaLink="false">http://daylerees.com/?p=249</guid>
		<description><![CDATA[Validation is an important part of many web applications. You can never trust your users, they have been plotting to destroy you for weeks, by abusing your forms with evil javascripts. We can&#8217;t let them win, the must not destroy our beautiful applications. Let&#8217;s validate all input provided by the user, that way they won&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>Validation is an important part of many web applications. You can never trust your users, they have been plotting to destroy you for weeks, by abusing your forms with evil javascripts.</p>
<p>We can&#8217;t let them win, the must not destroy our beautiful applications. Let&#8217;s validate all input provided by the user, that way they won&#8217;t be able to harm us at all.</p>
<p>Naturally Laravel has a library, aptly named &#8216;Validation&#8217; that will do all the hard work for us.</p>
<h2>Set up validation</h2>
<p>Let&#8217;s start by creating an imaginary form, close your eyes and imagine a nice long form with many fields&#8230; uh oh&#8230; how can I get you to open your eyes again..?</p>
<p>Right, I will assume you got fed up of waiting, have opened your eyes, and are back with me again, along with our imaginary form. Let&#8217;s get the input data from that form.</p>
<pre><code>$input = Input::get();
</code></pre>
<p>Now normally you don&#8217;t want to use the <code>get()</code> method, as its an easy way to populate your input array with extra data you don&#8217;t need. In fact the open source collaboration site github was a victim to mass assignment. I have used <code>get()</code> to simplify the tutorial, in your applications please build the input array only with the fields you need.</p>
<p>Now our input array now contains something that looks a little like this..</p>
<pre><code>array(
    'name' =&gt; 'John',
    'age'  =&gt; 15
)
</code></pre>
<p>Let&#8217;s validate these fields to make sure they make sense to our application, before we can start the validation process we need to create a set of rules that will be used to validate each field. With the validator class, rules are defined in an array format, let&#8217;s jump right in and take a look.</p>
<pre><code>$rules = array(
    'name'  =&gt; 'required|min:3|max:32|alpha',
    'age'   =&gt; 'required|integer|min:16'
);
</code></pre>
<p>Great, now we have some rules. The array key is the field that is being validated upon, and the array value contains a number of validation rules separate by a pipe | symbol.</p>
<p>In our case we are validating that both fields contain a value, by using the &#8216;required&#8217; rule. The length of the users name must be a minimum of 3 characters (min:3) and a maximum length of 32 characters (max:32). The &#8216;alpha&#8217; rule will check to make sure that the name field only contains letters.</p>
<p>Our age field must contain an <code>integer</code> and the value must be at least <code>16</code>, you see that the <code>min</code> rule has adapted to fit the content that its validating, very clever!</p>
<p>Don&#8217;t worry, we will cover all the validation rules later, for now let&#8217;s see the validation in action, here we go.</p>
<pre><code>$v = Validator::make($input, $rules);
</code></pre>
<p>We have made our validator object with the <code>make()</code> method, passing it our input array, and our rules array. Let&#8217;s see if it validates!</p>
<pre><code>if( $v-&gt;fails() )
{
    // code for validation failure <img src='http://daylerees.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />
}
else
{
    // code for validation success!
}
</code></pre>
<p>As you can see, we use the <code>fails()</code> method to check the result of the validation attempt, it will return <code>true</code> if the validation has failed, and <code>false</code> if it was successful.</p>
<p>If you prefer a more positive outlook on your validations, you could use the <code>passes()</code> method, which returns the opposite values..</p>
<pre><code>if( $v-&gt;passes() )
{
    // code for validation success!
}
else
{
    // code for validation failure <img src='http://daylerees.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />
}
</code></pre>
<p>There, now we are positive and can dance over rainbows with sparkleponies.</p>
<h2>Errors</h2>
<p>If your validation fails, which it will because our user is under 16 (sorry for slaying your sparklepony), you will want to find out what went wrong. The validator provides an <code>errors</code> Messages object which allows us to easily find the information we need.</p>
<p>The <code>errors</code> object has similar methods to the <code>Input</code> class, so I will not need to go over them all, let&#8217;s retrieve an array of errors for a specific field.</p>
<pre><code>$age_errors = $v-&gt;errors-&gt;get('age');
</code></pre>
<p>Now we have an array containing all of the errors associated with the age field..</p>
<pre><code>array(
    'The age must be at least 16.'
)
</code></pre>
<p>Most of the time I find myself using the <code>first()</code> method in my views, which returns the first array item if it exists, or null if it doesn&#8217;t. For example..</p>
<pre><code>{{ Form::label('username', 'Username') }}
{{ $errors-&gt;first('username') }}
{{ Form::text('username') }}
</code></pre>
<p>Now our validation errors will appear for this field if any are present. You can also pass a second parameter to the <code>first()</code> method to format the output..</p>
<pre><code>{{ $errors-&gt;first('username', '&lt;span class="error"&gt;:message&lt;/span&gt;') }}
</code></pre>
<p>Neat!</p>
<p>You can also use <code>has()</code> to check to see if an error exists, and <code>all()</code> to retrieve all errors as an array.</p>
<h2>Validation Rules</h2>
<p>Here is a list of validation rules, and their purpose.</p>
<p><strong><em>required</em></strong></p>
<p>Ensure that a value for a field is present, and is not an empty string.</p>
<p><strong><em>alpha</em></strong></p>
<p>The string must only consist of letters (alphabetical characters).</p>
<p><strong><em>alpha_num</em></strong></p>
<p>The string must only contain letters and numbers. Useful for usernames.</p>
<p><strong><em>alpha_dash</em></strong></p>
<p>The string must contain only letters, numbers, dashes or underscore characters. Useful for storing URL slugs.</p>
<p><strong><em>size:5</em></strong></p>
<p>(string) The string must be exactly five characters long.<br />
(numeric) The value must be five.</p>
<p><strong><em>between:5,10</em></strong></p>
<p>(string) The length of the string must be between five and ten characters.<br />
(numeric) The value must be between five and ten.</p>
<p><strong><em>min:5</em></strong></p>
<p>(string) The length of the string must be between five characters or more<br />
(numeric) The value must be equal to or greater than five.<br />
(file) The file size must be 5 kilobytes or more.</p>
<p><strong><em>max:5</em></strong></p>
<p>(string) The length of the string must be less than or equal to five.<br />
(numeric) The value must be less than or equal to five.<br />
(file) The file size must be 5 kilobytes or less.</p>
<p><strong><em>numeric</em></strong></p>
<p>The value must be numeric.</p>
<p><strong><em>integer</em></strong></p>
<p>The value must be an integer or whole number.</p>
<p><strong><em>in:red,green,blue</em></strong></p>
<p>Ensure that the value is contained within the list of values provided.</p>
<p><strong><em>not_in:pink,purple</em></strong></p>
<p>Ensure that none of the values provided match the value.</p>
<p><strong><em>confirmed</em></strong></p>
<p>The value of the field must match a confirmation field, named in the format &#8216;<fieldname>_confirmation&#8217;.</p>
<p><strong><em>accepted</em></strong></p>
<p>The field value must be equal to &#8216;yes&#8217; or 1. Useful for validating checkboxes.</p>
<p><strong><em>same:age</em></strong></p>
<p>The field value must match the field specified by the same rule.</p>
<p><strong><em>different:age</em></strong></p>
<p>The field value must not match the field specified by the same rule.</p>
<p><strong><em>match:/[a-z]+/</em></strong></p>
<p>The field value must match the provided regular expression.</p>
<p><strong><em>unique:users</em></strong></p>
<p>This is one of my favorites, the validator will look at the <code>users</code> database table, and make sure that the value is unique within the column that has the same name as the field name. Useful for making sure that duplicate usernames or email addresses don&#8217;t occur.</p>
<p>If you would like to specify an alternate column name, simply pass it as a second parameter..</p>
<pre><code>unique:users,nickname
</code></pre>
<p>You can also force the rule to ignore a provided <code>id</code> by passing it as a third parameter.</p>
<pre><code>unique:users,nickname,5
</code></pre>
<p><strong><em>exists:colors</em></strong></p>
<p>Acts as the opposite of <code>unique</code>, the value must already exist in the database table. Once more you can pass a second parameter to refer to another column.</p>
<p><strong><em>before:1984-12-12</em></strong></p>
<p>The date provided by the field, must have occurred before the date template provided to the <code>before</code> rule.</p>
<p>The before and after filters use strtotime() to calculate a timestamp for comparison, this means you can do some neat tricks like..</p>
<pre><code>before:next Thursday
</code></pre>
<p>Unfortunately I was on the one that added this functionality, so if it breaks you can go ahead and shout at me&#8230; sorry!</p>
<p><strong><em>after:1984-12-12</em></strong></p>
<p>Similar to before, only the date must occur after the date provided to the <code>after</code> rule.</p>
<p><strong><em>email</em></strong></p>
<p>The value must be a valid email address.</p>
<p><strong><em>url</em></strong></p>
<p>The value must match the format of an URL.</p>
<p><strong><em>active_url</em></strong></p>
<p>The value must match a valid active URL. <code>checkdnsr</code> is used to verify that the URL is active.</p>
<p><strong><em>mimes:png,mp3</em></strong></p>
<p>The value must be a $_FILE which whose MIME type matches the file extensions provided.<br />
You can add additional MIME types to the array in <code>config/mimes.php</code>.</p>
<p><strong><em>image</em></strong></p>
<p>The uploaded file must be an image.</p>
<h2>Custom Error Messages</h2>
<p>I find the custom error messages quite descriptive, but your clients might have their own ideas. Let&#8217;s see how we can customize our error messages to suit our needs.</p>
<p>You can edit the validation error messages directly by modifying the file <code>application/language/en/validation.php</code>&#8230;</p>
<pre><code>...
"after"          =&gt; "The :attribute must be a date after :date.",
"alpha"          =&gt; "The :attribute may only contain letters.",
"alpha_dash"     =&gt; "The :attribute may only contain letters, numbers, and dashes.",
...
</code></pre>
<p>Laravel replaces the <code>:attribute</code> marker with the name of the field. Other markers also exist within the rules, and their purpose is quite self explanatory.</p>
<p>If you would rather change the messages for a single form, rather than edit them globally, you can pass a third array of messages to the <code>Validator::make()</code> method.</p>
<pre><code>$messages = array(
    'same'    =&gt; 'The :attribute and <img src='http://daylerees.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ther must match, fool!',
    'size'    =&gt; 'The :attribute must be exactly :size , like duh!'
);

$v = Validator::make($input, $rules, $messages);
</code></pre>
<p>Great now we have custom messages! We can even specify error messages for individual fields, by setting the message key to <code>field_rule</code>, for example..</p>
<pre><code>$messages = array(
    'age_required'    =&gt; 'You need to have had at least one birthday!'
);
</code></pre>
<h2>Custom Validation Rules</h2>
<p>The validator allows you add extra rules to suit the needs of your application, let&#8217;s jump right in and take a look at how we register a new validation rule.</p>
<pre><code>Validator::register('superdooper', function($attribute, $value, $parameters){
    return $value == 'superdooper';
});
</code></pre>
<p>Our newly created validation rule <code>superdooper</code> will ensure that our value matches the string &#8216;superdooper&#8217;. Your custom validations should return <code>true</code> on success, or <code>false</code> on failure.</p>
<p>The <code>$attribute</code> value will be the name of the field being validated, and <code>$value</code> will of course contain the value.</p>
<p>The <code>$parameters</code> attribute contains an array of parameters that have been passed to the rule after the colon, and separated by commas.</p>
<p>As you have created a new validator, there will be no error messages associated with it yet, we will need to add one so that Laravel knows what to say when it fails. We can add an error message in the same way as we have previously..</p>
<pre><code>'superdooper' =&gt; 'The :attribute must be superdooper, ok trooper?!',
</code></pre>
<p>Once again you can pass the extra error message array as a third parameter to the <code>Validator::make()</code> method, or simply add it to your <code>application/language/en/validation.php</code> file for safe keeping.</p>
<h2>Validation Classes</h2>
<p>If we want to provide many new validation methods, or reuse them across a number if projects, it would be best to create a validation class. Validation classes extend Laravel&#8217;s data, and overload it with additional validation methods. The class is created in the <code>application/libraries</code> directory for easy loading, but you could place it elsewhere as long as it is registered with the <code>Autoloader</code> (later post). Let&#8217;s take a look at the class.</p>
<pre><code>&lt;?php

// application/libraries/validator.php

class Validator extends Laravel\Validator {

    public function validate_awesome($attribute, $value, $parameters)
    {
        return $value == 'awesome';
    }

}
</code></pre>
<p>As you can see our Validator class extends the <code>Laravel\Validator</code> namespaced core class and provides additional validations in the form of <code>validate_&lt;rulename&gt;</code> methods. The validation methods accept the same parameters as the <code>Validator::register()</code> closure, and work in the same way.</p>
<p>In order to use our new validation class, we will need to remove the existing alias for <code>Validator</code> from our <code>application/config/config.php</code> file. This way Laravel will use our created class instead of the one in the Laravel source folder.</p>
<p>You could use this method to replace the original validation methods with your own, for example you could create a <code>validate_size</code> method and calculate the size in an alternate format.</p>
<p>I would suggest adding custom error messages to the validation language file when using Validation classes, this will allow for a much easier migration to another project, and will not require any &#8216;source-digging&#8217; to find all the messages used.</p>
<p>In the next post, we will cover some typical form validation scenarios that are common to web applications, this includes input forms, edit forms, form re-population and more.</p>
]]></content:encoded>
			<wfw:commentRss>http://daylerees.com/2012/04/30/laravel-validation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Laravel: Encryption</title>
		<link>http://daylerees.com/2012/04/26/laravel-encryption/</link>
		<comments>http://daylerees.com/2012/04/26/laravel-encryption/#comments</comments>
		<pubDate>Thu, 26 Apr 2012 17:12:53 +0000</pubDate>
		<dc:creator>Dayle</dc:creator>
				<category><![CDATA[Laravel Tutorials]]></category>

		<guid isPermaLink="false">http://daylerees.com/?p=246</guid>
		<description><![CDATA[Sometimes you need to protect your important data. Laravel provides two different methods to help you do that. One-way and two-way encryption. Let&#8217;s take a look at these methods. One Way Encryption One way encryption is the best way to store user passwords, or other sensitive data. One way means that your data can be [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes you need to protect your important data. Laravel provides two different methods to help you do that. One-way and two-way encryption. Let&#8217;s take a look at these methods.</p>
<h2>One Way Encryption</h2>
<p>One way encryption is the best way to store user passwords, or other sensitive data. One way means that your data can be converted into an encrypted string, but due to a complex algorithm with painful maths, reversing the process is not possible.</p>
<p>This makes storing passwords a doddle! Your customers don&#8217;t have to worry about you knowing their passwords, but you are still able to compare them (by hashing the password they provide) or change the password if needed.</p>
<p><code>Note that hashing is the process of creating a hash or encrypted string from another string.</code></p>
<p>Let&#8217;s take a look at how password hashing works with one way encryption.</p>
<pre><code>$pass = Input::get('password');
</code></pre>
<p>Now we have retrieved the password from our &#8216;create user&#8217; form, but it&#8217;s in plain-text! Let&#8217;s hash it quickly so we can store it securely in our database.</p>
<pre><code>$pass = Hash::make($pass);
</code></pre>
<p>We have used another of Laravel&#8217;s highly expressive methods, this time <code>make()</code>ing a new <code>Hash</code>. Our <code>$pass</code> value will now contain a bcrypt encrypted version of our password, neat!</p>
<p>Let&#8217;s say that our user has entered their password to login, and now we need to check to see if its authentic before they can be logged into the system. We can simply compare our hash to the value stored in the database with the <code>check()</code> method.</p>
<pre><code>$pass = Input::get('password');
if ( Hash::check($pass, $user-&gt;password) )
{
    // auth successful
}
</code></pre>
<p>The <code>check()</code> method accepts two parameters, the plain-text value provided by your user, and the hashed password that you have stored. It returns a boolean value to indicate whether the true values match or not.</p>
<p>What if we want to decode our data at a later date? Let&#8217;s two way encrypt it.</p>
<h2>Two Way Encryption</h2>
<p>Two way encryption, allows you to return your encrypted data to its original form, kind of like those spy code sheets you played with when you were a kid!</p>
<p>The Laravel Crypter class uses AES-256 encryption which is provided by the Mcrypt PHP extension, so make sure that this PHP extension has been installed before attempting to use the class!</p>
<p>The Crypter class works using two simple methods, <code>encrypt()</code> and <code>decrypt()</code>, let&#8217;s take a look at encrypting a string.</p>
<pre><code>$secret = Crypter::encrypt('I actually like Hello Kitty');
</code></pre>
<p>Now our dirty little secret has been AES-256 encrypted, and the result has been returned. This would be of no use if we couldn&#8217;t decrypt the secret at a later date. Let&#8217;s look at how you can decrypt an encrypted piece of data.</p>
<pre><code>$decrypted_secret = Crypter::decrypt($secret);
</code></pre>
<p>Easy as that! Simply hand the encrypted string to the <code>decrypt()</code> and the decrypted result is handed back.</p>
<p>Enjoy using the Crypter class to simulate the feeling of using your super secret decoder rings you got that one time in a cereal box!</p>
]]></content:encoded>
			<wfw:commentRss>http://daylerees.com/2012/04/26/laravel-encryption/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Laravel: The IoC Container</title>
		<link>http://daylerees.com/2012/04/20/laravel-the-ioc-container/</link>
		<comments>http://daylerees.com/2012/04/20/laravel-the-ioc-container/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 16:49:57 +0000</pubDate>
		<dc:creator>Dayle</dc:creator>
				<category><![CDATA[Laravel Tutorials]]></category>

		<guid isPermaLink="false">http://daylerees.com/?p=240</guid>
		<description><![CDATA[The IoC container is a tricky subject, many people are confused by its description in the documentation, and for a short time I was included in those people. A great deal of research, and the support of the fantastic Laravel community (join us in #laravel on freenode IRC) has cleared up the topic nicely. Hopefully [...]]]></description>
			<content:encoded><![CDATA[<p>The IoC container is a tricky subject, many people are confused by its description in the documentation, and for a short time I was included in those people. A great deal of research, and the support of the fantastic Laravel community (join us in #laravel on freenode IRC) has cleared up the topic nicely. Hopefully I will be able to shed some light on this mysterious topic.</p>
<p>IoC stands for Inversion of Control, I don&#8217;t want to complicate things with a full description, there are many online articles which will cover the nerdier side of this topic. Instead think of the container as &#8216;Inverting the Control&#8217; or &#8216;Handing control back to Laravel&#8217; to resolve our objects.</p>
<p>That&#8217;s what the container is all about, resolving objects. Other than its use for injecting dependencies for use in unit tests (we will cover this later) you can simply think of the IoC container as a &#8216;shortcut&#8217; for resolving complex objects, or following a singleton pattern, without the usual class associated with the pattern. More on singletons later, let&#8217;s have a look at registering a objects with the container.</p>
<h2>Registering Objects</h2>
<p>Let&#8217;s use our imaginations, like the big purple dinosaur on the TV taught us. We will be imagining a class called &#8216;Discoball&#8217; which will be used all over our application for various groovy purposes.</p>
<p>Unfortunately, our Discoball class requires a lot of configuration before it can be used, let&#8217;s have a look at that.</p>
<pre><code>$db = new Discoball(Discoball::SHINY);
$db->configure_shinyness('max');
$db->spin_speed('8900rpm');</code></pre>
<p>Woah! That&#8217;s a lot of settings. Now it would soon get boring to have to instantiate and setup our discoball every time we want to use it. Let&#8217;s let the IoC container instantiate it for us, and jump right in with a code sample.</p>
<p>I like to put this code into start.php, but you can put it anywhere you like, as long as your objects are registered before you try to resolve them.</p>
<pre><code>// application/start.php
IoC::register('discoball', function() {

    // instantiate our object as before
    $db = new Discoball(Discoball::SHINY);
    $db-&gt;configure_shinyness('max');
    $db-&gt;spin_speed('8900rpm');

    // hand the object as the result of the closure
    return $db;
});
</code></pre>
<p>We use the <code>IoC::register()</code> method to register our object with the controller. The first parameter is a string that will be used to resolve the object later, I used the word &#8216;discoball&#8217; as it made the most sense to me. The second parameter is a closure that we can use to instantiate our object.</p>
<p>Inside the closure you will see the familiar discoball configuration code, and we will return the configured discoball object from the closure.</p>
<p>Great! Our object is registered, and that&#8217;s all there is to the Io&#8230; just kidding. Let&#8217;s have a look at how we can use our registered object.</p>
<h2>Resolving Objects</h2>
<p>Now we have our disco ball registered, let&#8217;s see how we can get it back. Let&#8217;s make a call to resolve.</p>
<pre><code>$db = IoC::resolve('discoball');</code></pre>
<p>And that&#8217;s it! Instead of creating and configuring a new instance of our discoball each time, we make a call to the <code>resolve()</code> method, passing the string that identifies the object and the IoC container will execute the closure we created in the first section, and return our instantiated and configured discoball object.</p>
<p>Handy, and saves many lines of code!</p>
<p>You can register and resolve as many objects as you want, go ahead and try it. For now lets move on to singletons.</p>
<h2>Singletons</h2>
<p>Resolving our discoball is useful, but what if our discoball was expensive on resources to instantiate, or should only be instantiated once? The register method will not be useful in this case, since the closure is executed with every call to <code>resolve()</code> and a new instance of the object is returned each time. This is where the singleton design pattern comes in.</p>
<p>The singleton design pattern involves writing your classes in a certain way, so that they can be called using a static method, and will always return the same instance of itself. This way the class is instantiated only once.</p>
<p>For more information on the Singleton design pattern, I would suggest a quick Google search, or check out the PHP API which has an article on the subject.</p>
<p>Singletons can be useful, but they require a certain class structure to be able to use them. The IoC container has a <code>singleton()</code> method which makes the process a lot more simple, and does not require any special kind of class. Let&#8217;s register our discoball as a singleton instead..</p>
<pre><code>// application/start.php

IoC::singleton('discoball', function() {

    // instantiate our object as before
    $db = new Discoball(Discoball::SHINY);
    $db-&gt;configure_shinyness('max');
    $db-&gt;spin_speed('8900rpm');

    // hand the object as the result of the closure
    return $db;
});
</code></pre>
<p>As you can see, the process is almost identical to registering an object, except that we use the method <code>singleton()</code> which accepts the same parameters.</p>
<p>When we resolve our discoball, the closure will only be run the first time <code>resolve()</code> is called, the resulting object will be stored, and any future calls to the <code>resolve()</code> method will return the same object instance. For example..</p>
<pre><code>// closure is executed, and a discoball
// instance is returned
$db = IoC::resolve('discoball');

// the same instance of the discoball
// in the above statement is returned
$another = IoC::resolve('discoball');
</code></pre>
<p>Great! It&#8217;s also worth noting that you can pass an already instantiated object as a second parameter to the <code>singleton()</code> method, and it will be returned by all future requests to <code>resolve()</code> for example..</p>
<pre><code>$db = new Discoball(Discoball::SHINY);
IoC::singleton('discoball', $db);

// get hold of our discoball
$ball = IoC::resolve('discoball');
</code></pre>
<p>In a future post we will discuss using the IoC container and dependency injection in combination with unit testing.</p>
<hr />
<p>Thanks to Andrew Smith and Julien Tant (AoSix) for buying the book. Julien had the following to say..</p>
<blockquote>
<p>Hey Dayle, thanks a lot for this book, the Laravel framework is just awesome ! If any french guys read this, visit http://www.laravel.fr/ !</p>
</blockquote>
<p>Thanks guys, and great work translating the tutorials to French!</p>
<p>Also thanks to Proger_XP for buying the book and translating my tutorials to Russian, which are available at Laravel.ru. Great work!</p>
]]></content:encoded>
			<wfw:commentRss>http://daylerees.com/2012/04/20/laravel-the-ioc-container/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Laravel: Handling Input</title>
		<link>http://daylerees.com/2012/04/15/laravel-handling-input/</link>
		<comments>http://daylerees.com/2012/04/15/laravel-handling-input/#comments</comments>
		<pubDate>Sun, 15 Apr 2012 22:11:06 +0000</pubDate>
		<dc:creator>Dayle</dc:creator>
				<category><![CDATA[Laravel Tutorials]]></category>

		<guid isPermaLink="false">http://daylerees.com/?p=233</guid>
		<description><![CDATA[Now that we know how to create forms, we need to learn how to handle the input that has been sent by them. As always, Laravel has provided an ultra clean way of dealing with your input data. No need to interact with PHP arrays such as $_POST, $_GET and $_FILES. Let&#8217;s be honest, those [...]]]></description>
			<content:encoded><![CDATA[<p>Now that we know how to create forms, we need to learn how to handle the input that has been sent by them. As always, Laravel has provided an ultra clean way of dealing with your input data. No need to interact with PHP arrays such as <code>$_POST</code>, <code>$_GET</code> and <code>$_FILES</code>. Let&#8217;s be honest, those look ugly.</p>
<h2>Request data</h2>
<p>Let&#8217;s use the Input class to handle this instead.</p>
<pre><code>$panda = Input::get('panda');
</code></pre>
<p>Now we have a Panda! Great.. we have too many already. One thing you need to remember about the <code>get()</code> method on the Input class, is that it doesn&#8217;t refer to <code>$_GET</code> data, <code>get()</code> is just a nice and expressive short method name for retrieving all kinds of data. The input class adds responds to <code>get()</code> with all kinds of request data, including <code>$_POST</code>.</p>
<p>If a piece of request data isn&#8217;t set, the Input class will return <code>null</code>. If you pass a second parameter to the <code>get()</code> method and the index doesn&#8217;t exist, then the method will return the second parameter instead. Very useful!</p>
<pre><code>$panda = Input::get('panda', 'Muffin');
</code></pre>
<p>If you would like to retrieve the entire request array, simply skip the index. Easy as that.</p>
<pre><code>$morepandas = Input::get();
</code></pre>
<p>By default the <code>get()</code> array won&#8217;t includes values from the <code>$_FILES</code> array, however if you use <code>all()</code> instead of <code>get()</code> it will contain files too.</p>
<pre><code>$pandas_and_files = Input::all();
</code></pre>
<p>If you would like to check if a piece of post data exists, without actually returning it, simply use the elegant and highly expressive <code>has()</code> method, which will return a boolean result.</p>
<h2>Files</h2>
<p>To access an element from the <code>$_FILES</code> array, simple make a call to the <code>Input::file()</code> method, for example..</p>
<pre><code>$file = Input::file('spoon');
</code></pre>
<p>If you simply want to retrieve a file attribute, then add a period, and an attribute key to the first parameter, for example to retrieve the file size..</p>
<pre><code>$size = Input::file('spoon.size');
</code></pre>
<p>Once again, calling the method without a parameter will retrieve the full array of files.</p>
<pre><code>$files = Input::file();
</code></pre>
<h2>Flash Data</h2>
<p>Flash data is a useful method of storing data for use in the next request, this can be a useful method of repopulating forms.</p>
<p>To <code>flash</code> all request data to the session, for it to be accessible in the next request, simply use the <code>flash()</code> method.</p>
<pre><code>Input::flash();
</code></pre>
<p>If you only want to flash a portion of the current request data, simply pass &#8216;only&#8217; as the first parameter to the method, and an array of field names that you wish <code>flashed</code> as the second parameter.</p>
<pre><code>Input::flash('only', array('betty', 'simon'));
</code></pre>
<p>Now we will take Betty and Simon with us to the next request. Alternatively we could specify a list of fields that we don&#8217;t want to take with us using the <code>except</code> option, for example..</p>
<pre><code>Input::flash('except', array('uncle_bob'));
</code></pre>
<p>There, now we can leave Uncle Bob behind, he&#8217;s an arrogant soul, and dislikes our national animal the red panda.</p>
<p>Now we can use the usual <code>Redirect::to()</code> method to move to a new request. From here we can use the expressive <code>Input::old()</code> method to retrieve a value that has been <code>flashed</code> from a previous request.</p>
<pre><code>$betty = Input::old('betty');
</code></pre>
<p>As you can see, Betty has survived the transition. You can think of flash data as those fuzzy transporter pads from Star Trek, moving Kirk and his buddies from one request to the next.</p>
<p>Once again you can skip the parameter to return a full array of flash data.</p>
<pre><code>$people = Input::old();
</code></pre>
<p>You can use the <code>had()</code> method to see if an index of flash data exists.</p>
<pre><code>Input::had('uncle_bob');
</code></pre>
<p>Of course not, we hate Uncle Bob.</p>
<p>Laravel wouldn&#8217;t be the framework it is, without its wonderful shortcuts and expressive methods. Let&#8217;s have a look at a prime example of this in action.</p>
<pre><code>return Redirect::to('party')-&gt;with_input();
</code></pre>
<p>The <code>with_input()</code> method will flash all of our request data for us, it also accepts the same <code>only</code> and <code>except</code> methods as our <code>flash()</code> method.</p>
<pre><code>return Redirect::to('party')-&gt;with_input('only', array('betty', 'simon'));
return Redirect::to('party')-&gt;with_input('except', array('uncle_bob'));
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://daylerees.com/2012/04/15/laravel-handling-input/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Laravel: Links and URLs</title>
		<link>http://daylerees.com/2012/04/15/laravel-links-and-urls/</link>
		<comments>http://daylerees.com/2012/04/15/laravel-links-and-urls/#comments</comments>
		<pubDate>Sun, 15 Apr 2012 12:02:41 +0000</pubDate>
		<dc:creator>Dayle</dc:creator>
				<category><![CDATA[Laravel Tutorials]]></category>

		<guid isPermaLink="false">http://daylerees.com/?p=227</guid>
		<description><![CDATA[Our application might get a little boring if we only have one page, and I&#8217;m sure the user would get peeved quite quickly if they had to type out the full URI each time to switch pages. Fortunately hyper-links are here to save the day. If you haven&#8217;t been living under a rock for the [...]]]></description>
			<content:encoded><![CDATA[<p>Our application might get a little boring if we only have one page, and I&#8217;m sure the user would get peeved quite quickly if they had to type out the full URI each time to switch pages. Fortunately hyper-links are here to save the day.</p>
<p>If you haven&#8217;t been living under a rock for the past couple of decades you will already know what hyper-links are, and I won&#8217;t bore you with the technical explanation. Before we have a look at links let&#8217;s take a look at how Laravel handles its URLs.</p>
<h2>Retrieving URLs</h2>
<p>First let&#8217;s take a look at a problem. You see frameworks have very unique URL structures, some may have an index.php in them, some installations won&#8217;t. Others will have complex routes. In most cases using a relative URL like you would on another website would lead to trouble in the long run. If you chose to provide full URL&#8217;s to everything, and decided to move the application at a later date, you might find yourself abusing the find and replace function of your favorite editor.</p>
<p>Why not let Laravel do all the hard work? Laravel knows the full URL to your application, it knows whether or not you are using URL rewriting. It even knows about your routes. Let&#8217;s take advantage of this information by using the URL class to generate some site URLs.</p>
<p>Let&#8217;s start by finding the URL to the root of our website. We can use the <code>base()</code> method for this.</p>
<pre><code>echo URL::base();
</code></pre>
<p>Great! Now we have the full URL to our site, with or without the <code>index.php</code> on the end, it all depends on your current setup. What about the current URL, the one that is being routed at the moment, can we get that? You betcha! Simply use the <code>current()</code> method.</p>
<pre><code>echo URL::current();
</code></pre>
<p>By default, Laravel will strip off the query string, if one is appended to the URL. If we want to retrieve the current URL along with the query string, we can use the <code>full()</code> method instead.</p>
<pre><code>echo URL::full();
</code></pre>
<p>Knowing our base URL and current URL can be handy, but it would be more useful if we could get the URL to other routes or pages, then we could create links.</p>
<p>To generate a URL to a route, we use the <code>to()</code> method, and hand it the route we are trying to retrieve, this is much easier than specifying the full path, for example..</p>
<pre><code>echo URL::to('my/route');
</code></pre>
<p>If we wan&#8217;t to link to this page securely, via the HTTPS protocol we can use the method <code>to_secure()</code> instead.</p>
<pre><code>echo URL::to_secure('my/route');
</code></pre>
<p>Do you remember being taught about named routes in the routing post? Of course you do! Here&#8217;s an example of one again..</p>
<pre><code>Route::get('login', array('as' =&gt; 'login', 'do' =&gt; function() {
    // some code
}));
</code></pre>
<p>Here we have a route that we have named &#8216;login&#8217; using the &#8216;as&#8217; array key. Well I told you that it would be useful later, and now is the time for named routes to shine. Let&#8217;s make a link to our named &#8216;login&#8217; route..</p>
<pre><code>echo URL::to_route('login');
</code></pre>
<p>Woah! Very clean and expressive I think you will agree. What if we need to supply parameters to our route? Simple, just pass an array of parameters as a second parameter to the <code>to_route()</code> method. Let&#8217;s imagine for a second that our login route looks more like this&#8230;</p>
<pre><code>Route::get('my/(:any)/login/(:any)/page')..
</code></pre>
<p>It&#8217;s a terrible route, please don&#8217;t use ugly URL&#8217;s like this one, but it will help to illustrate a point. You see if you pass parameters to the <code>to_route()</code> method, Laravel will automatically work out which order they should appear in the URL, and return the full URL with the parameters in the right place, neat!</p>
<pre><code>echo URL::to_route('login', array(5, 7));
</code></pre>
<p>The above method would give us..</p>
<pre><code>http://myapp/my/5/login/7/page
</code></pre>
<p>Great! Now our routes will look squeaky clean.. as long as we don&#8217;t create routes as complicated as that one.</p>
<p>So that&#8217;s routes cleared up, but we shouldn&#8217;t forget controllers. No one likes to be left out. Fortunately there&#8217;s a nice and clean way to create a link to a controller action. Simply use the <code>to_action()</code> method, for example..</p>
<pre><code>echo URL::to_action('dashboard@home');
</code></pre>
<p>Simply pass the controller name and action, separated by an <code>@</code> (at) symbol. Once again you can pass an array of extra parameters as a second parameter to the <code>to_action()</code> method if you need to.</p>
<p>If we are dealing with assets, a CSS style-sheet for example, rather than routes pages we will need a very different URL. We can&#8217;t use <code>URL::to()</code> because that might put an <code>index.php</code> in the URL, or resolve it to one of our routes.</p>
<p>Instead we can use the <code>to_asset()</code> method to generate a correct link. Simply pass the application relative path to our style-sheet, and Laravel will take care of the rest.</p>
<pre><code>echo URL::to_asset('css/style.css');
</code></pre>
<p>This line will give us..</p>
<pre><code>http://myapp/css/style.css
</code></pre>
<p>These methods are already very handy, but Laravel takes this a step further by providing shorter <code>helper</code> methods which look great when used in our views. Here is a list of these helpers, and their longer alternatives.</p>
<table>
<thead>
<tr>
<th>Helper</th>
<th>Method</th>
</tr>
</thead>
<tbody>
<tr>
<td>url()</td>
<td>URL::to()</td>
</tr>
<tr>
<td>asset()</td>
<td>URL::to_asset()</td>
</tr>
<tr>
<td>route()</td>
<td>URL::to_route()</td>
</tr>
<tr>
<td>action()</td>
<td>URL::to_action()</td>
</tr>
</tbody>
</table>
<h2>Generating Links</h2>
<p>Now that we can retrieve our site links, the next logical step would be to use them to create hyper-links, now I know what you&#8217;re thinking, we can do it like this..</p>
<pre><code>&lt;a href="&lt;?php echo URL::to('my/page'); ?&gt;"&gt;My Page&lt;/a&gt;
</code></pre>
<p>Sure that would work, but it&#8217;s a little ugly. In Laravel if something is a little ugly, there is always a better way of handling it. Links are no exception.</p>
<p>Why don&#8217;t we use the HTML class to generate a link? After all, that&#8217;s what the HTML class is for. It is used to generate all kinds of HTML tags.</p>
<pre><code>&lt;?php echo HTML::link('my/page', 'My Page'); ?&gt;
</code></pre>
<p>That looks a lot better! Let&#8217;s see the result.</p>
<pre><code>&lt;a href="http://localhost/develop/index.php/my/page"&gt;My Page&lt;/a&gt;
</code></pre>
<p>If you are an SEO ninja, and cannot stand to see a link without a title attribute, simply pass an extra array.</p>
<pre><code>&lt;?php echo HTML::link('my/page', 'My Page', array('title' =&gt; 'My page!')); ?&gt;
</code></pre>
<p>Which gives..</p>
<pre><code>&lt;a href="http://localhost/develop/index.php/my/page" title="My page!"&gt;My Page&lt;/a&gt;
</code></pre>
<p>One of the great features of Laravel is how consistent its method naming is, many of the <code>HTML::link</code> methods follow a similar naming pattern as the <code>URL::to</code> methods, which makes them easy to remember. Let&#8217;s take a look at how we can link to a secure page (via HTTPS).</p>
<pre><code>HTML::link_to_secure('my/page', 'My Page');
</code></pre>
<p>We can also use <code>link_to_route</code>, to create a link to a named route just like we did with the URL library.</p>
<pre><code>HTML::link_to_route('login', 'Login!');
</code></pre>
<p>Once again we can use the <code>link_to_action()</code> method to link to a controller-action pair, for example..</p>
<pre><code>HTML::link_to_action('account@login', 'Login!');
</code></pre>
<p>Laravel even gives us a method of easily creating &#8216;mailto&#8217; links from an email address. Let&#8217;s take a look.</p>
<pre><code>HTML::mailto('me@daylerees.com', 'Mail me!');
</code></pre>
<p>Nice and clean!</p>
<p>Now that you know how to create URL&#8217;s and links, your applications will start to grow in size, covering many routes until they consume our planet and take over the unive&#8230;</p>
<p>Your applications will be a lot more interesting!</p>
]]></content:encoded>
			<wfw:commentRss>http://daylerees.com/2012/04/15/laravel-links-and-urls/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Laravel: Forms</title>
		<link>http://daylerees.com/2012/04/15/laravel-forms/</link>
		<comments>http://daylerees.com/2012/04/15/laravel-forms/#comments</comments>
		<pubDate>Sun, 15 Apr 2012 11:23:35 +0000</pubDate>
		<dc:creator>Dayle</dc:creator>
				<category><![CDATA[Laravel Tutorials]]></category>

		<guid isPermaLink="false">http://daylerees.com/?p=224</guid>
		<description><![CDATA[Forms are an important part of any web-based application. They help control the flow of the application, allow us to receive input from our users and make decisions that effect the functionality of our applications. They are also my least favorite thing in the world to write. Fortunately for me, Laravel&#8217;s form class takes care [...]]]></description>
			<content:encoded><![CDATA[<p>Forms are an important part of any web-based application. They help control the flow of the application, allow us to receive input from our users and make decisions that effect the functionality of our applications. They are also my least favorite thing in the world to write.</p>
<p>Fortunately for me, Laravel&#8217;s form class takes care of a lot of the hard work for us, by providing useful methods for generating common form elements. Let&#8217;s use the form class to create a simple web form in one of our views.</p>
<h2>Creating Forms</h2>
<pre><code>// form.php
&lt;?php echo Form::open('my/route'); ?&gt;

    &lt;!-- username field --&gt;
    &lt;?php echo Form::label('username', 'Username'); ?&gt;
    &lt;?php echo Form::text('username'); ?&gt;

    &lt;!-- password field --&gt;
    &lt;?php echo Form::label('password', 'Password'); ?&gt;
    &lt;?php echo Form::password('password'); ?&gt;

    &lt;!-- login button --&gt;
    &lt;?php echo Form::submit('Login');

&lt;?php echo Form::close(); ?&gt;
</code></pre>
<p>Take a moment, stare at the form source, you have never seen a form so clean. Say it out loud to yourself, go on.. I will wait.</p>
<blockquote>
<p>I have never seen a form so clean.</p>
</blockquote>
<p>You are right, its beautiful, let&#8217;s have a look at the generated source to make sure I&#8217;m not just teaching you wrong, you know, for fun?</p>
<pre><code>&lt;form method="POST" action="http://mysite/my/route" accept-charset="UTF-8"&gt;

    &lt;!-- username field --&gt;
    &lt;label for="username"&gt;Username&lt;/label&gt;
    &lt;input type="text" name="username" id="username"&gt;

    &lt;!-- password field --&gt;
    &lt;label for="password"&gt;Password&lt;/label&gt;
    &lt;input type="password" name="password" id="password"&gt;

    &lt;!-- login button --&gt;
    &lt;input type="submit" value="Login"&gt;

&lt;/form&gt;
</code></pre>
<p>Great, it worked! I mean of course it did! Let&#8217;s go over the form line by line to see how it works, on our first line we have the <code>Form::open()</code> method, which creates a form open tag for us.</p>
<p>The first parameter to the method is the URI we wish to submit the form to. The second parameter is the <code>METHOD</code> used to submit the form, if you don&#8217;t provide a method as a string Laravel will assume that you want a <code>POST</code> form, which is the most common usage.</p>
<p>The third parameter is also optional, you can pass an array of <code>attribute =&gt; value</code> pairs to add extra attributes to the <code>&lt;form&gt;</code> tag. For example if you wished to target the form with Javascript you may want to pass <code>array('id' =&gt; 'myform')</code> as the third parameter to give the element an <code>id</code>.</p>
<p>To submit a form to a secure URI (https) you will need to use the <code>open_secure()</code> method instead of <code>open()</code>, it accepts the same parameters.</p>
<p>If you wish to be able to have files uploaded from your form, it will need to use <code>multipart/data</code>, use <code>open_for_files()</code> instead of the <code>open()</code> method. This method also accepts the same parameters.</p>
<p>Finally if you wish to submit to a secure URI, and have files uploaded you will need to use the <code>open_secure_for_files()</code> method, which once again accepts the same parameters, and is a combination of both <code>open_secure()</code> and <code>open_for_files()</code>.</p>
<h2>Adding Labels</h2>
<p>The next line contains the <code>Form::label()</code> method which is used to create a <code>&lt;label&gt;</code> element. The first parameter is the <code>name</code> of the input element that it describes to be used in the <code>for=""</code> attribute. The second parameter is what will be used as the content of the <code>label</code> element. You can pass an array as an optional third parameter to apply extra HTML element attributes.</p>
<h2>Generating Inputs</h2>
<p>Next we have the input generators, these methods help to generate all of the HTML elements that are common to forms. In the example above we use the <code>text()</code> and <code>password()</code> method to generate <code>&lt;input type="text"..</code> and <code>&lt;input type="password"..</code> elements.</p>
<p>The first parameter to the method, is the value of the elements <code>name</code> attribute, the second optional parameter is the default value of the element. Once more we can pass an array of HTML attributes as an optional third parameter, are you starting to see a pattern yet?</p>
<p>The <code>textarea()</code> and <code>hidden()</code> fields also accept the same parameters.</p>
<p>Checkboxes can be created using the <code>checkbox()</code> method, with the first parameter being the name of the element, the second being the value, and the third option is an optional boolean switch to set whether the element is initially checked or not. The fourth optional parameter again sets attributes, in fact.. go ahead an assume all future inputs accept an attributes array as their optional final parameter. Let&#8217;s have a look at a checkbox generator..</p>
<pre><code>&lt;?php echo Form::checkbox('admin', 'yes', true, array('id' =&gt; 'admin-checker')); ?&gt;
</code></pre>
<p>The <code>radio()</code> method creates radio buttons, and shares the same parameters as the <code>checkbox()</code> method.</p>
<p>Next we have drop downs, the most awkward of all form elements. Fortunately all we need to do is pass a name, an array of <code>value =&gt; label</code> options, and an optional parameter to state which option should be selected by default to the <code>select()</code> method. Our dropdown will then be generated for us, for example..</p>
<pre><code>Form::select('roles', array(
    0 =&gt; 'User',
    1 =&gt; 'Member',
    2 =&gt; 'Editor',
    3 =&gt; 'Administrator'
), 2);
</code></pre>
<p>and we get..</p>
<pre><code>&lt;select name="roles"&gt;
    &lt;option value="0"&gt;User&lt;/option&gt;
    &lt;option value="1"&gt;Member&lt;/option&gt;
    &lt;option value="2" selected="selected"&gt;Editor&lt;/option&gt;
    &lt;option value="3"&gt;Administrator&lt;/option&gt;
&lt;/select&gt;
</code></pre>
<p>Great! Now it&#8217;s time to submit our form.</p>
<h2>Generating Buttons</h2>
<p>The <code>submit()</code> and <code>button()</code> generator methods both accept the same parameters, the first being the <code>value</code> of the HTML element, and the second being the usual array of attributes.</p>
<pre><code>Form::submit('Login');
</code></pre>
<h2>Secret Inputs</h2>
<p>There are also a number of extra generation methods for less common form inputs that aren&#8217;t covered by the documentation. Here is a listing of them, with their parameters.</p>
<pre><code>Form::search($name, $value = null, $attributes = array());
Form::email($name, $value = null, $attributes = array());
Form::telephone($name, $value = null, $attributes = array());
Form::url($name, $value = null, $attributes = array());
Form::number($name, $value = null, $attributes = array());
Form::date($name, $value = null, $attributes = array());
Form::file($name, $attributes = array());
</code></pre>
<h2>CSRF Token</h2>
<p>If you intend to use the <code>CSRF</code> filter (which will be covered in a later post) you can add the CSRF token to your form by using the method <code>token()</code>, for example..</p>
<pre><code>Form::token();
</code></pre>
<h2>Form Macros</h2>
<p>Laravel has provided many different input methods, but what if we need something a little more custom? Fortunately Laravel has provided the <code>macro</code> method to allow us to create our own input generators.</p>
<p>By passing an input name, and a closure to the <code>macro</code> method we can define our own input generator, let&#8217;s take a look.</p>
<pre><code>Form::macro('shoe_size', function() {
    return '&lt;input type="show_size" /&gt;';
});
</code></pre>
<p>Now we can use the Form class to generate our shoe size field in the same way as any other input, for example..</p>
<pre><code>&lt;?php echo Form::shoe_size(); ?&gt;
</code></pre>
<p>If you need to use parameters, simply add them as parameters to the closure. Enjoy creating your own unique input generators!</p>
]]></content:encoded>
			<wfw:commentRss>http://daylerees.com/2012/04/15/laravel-forms/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Trick: Chainable Libraries</title>
		<link>http://daylerees.com/2012/04/13/trick-chainable-libraries/</link>
		<comments>http://daylerees.com/2012/04/13/trick-chainable-libraries/#comments</comments>
		<pubDate>Fri, 13 Apr 2012 23:11:09 +0000</pubDate>
		<dc:creator>Dayle</dc:creator>
				<category><![CDATA[Laravel Tricks]]></category>

		<guid isPermaLink="false">http://daylerees.com/?p=220</guid>
		<description><![CDATA[You may have seen Laravel&#8217;s core libraries use method chaining as an elegant way of providing multiple user definable settings to a library, for example the Fluent Query Builder allows you to chain methods together to build your SQL query before executing it, like this.. DB::table('users')-&#62;where('name', '=', 'dayle')-&#62;take(5)-&#62;get(); It&#8217;s a system that simply makes sense [...]]]></description>
			<content:encoded><![CDATA[<p>You may have seen Laravel&#8217;s core libraries use method chaining as an elegant way of providing multiple user definable settings to a library, for example the Fluent Query Builder allows you to chain methods together to build your SQL query before executing it, like this..</p>
<pre><code>DB::table('users')-&gt;where('name', '=', 'dayle')-&gt;take(5)-&gt;get();
</code></pre>
<p>It&#8217;s a system that simply makes sense to use, and is very clear to read. Today I am going to help you build chainable classes, so that your libraries will start to feel more &#8216;Laravelish&#8217;. (If that isn&#8217;t a real word we need to make it one.)</p>
<p>I&#8217;m going to start by showing you a chainable class, all done.</p>
<pre><code>class Ball
{
    private $size = 1;
    private $color = 'blue';
    private $texture = 'squishy';

    // creator
    public static function make()
    {
        $ball = new Ball();
        return $ball;
    }

    // chain
    public function size($size)
    {
        $this-&gt;size = $size;
        return $this;
    }

    // chain
    public function color($color)
    {
        $this-&gt;color = $color;
        return $this;
    }

    // chain
    public function texture($texture)
    {
        $this-&gt;texture = $texture;
        return $this;
    }

    // trigger
    public function get()
    {
        return "This is a {$this-&gt;texture} {$this-&gt;color} ball, size {$this-&gt;size}.";
    }
}
</code></pre>
<p>I bet its not as complicated as you thought it would be! Before we can look at how it works, first you will need to know the three parts of a chainable class. I will use my own names for these parts, feel free to borrow them!</p>
<p><strong><em>Creator</em></strong></p>
<p>The creator method is normally static, and is used to create a new instance of the class. It will always return the class instance as the result of the method. In my example the creator is <code>make()</code>.</p>
<p><strong><em>Chains</em></strong></p>
<p>Chains are methods which alter the class in some way. They are non-static public methods, which set class attributes with the new settings passed to them. Chains will always return the current instance of the class, which is <code>$this</code>.</p>
<p><strong><em>Triggers</em></strong></p>
<p>Trigger methods are found at the end of the chain. They are the methods that make use of all of class attributes we have changed. They either perform an action, or return a result.</p>
<p>Let&#8217;s have a closer look at each part of our class, first the <code>Creator</code> method <code>make()</code>.</p>
<pre><code>// creator
public static function make()
{
    $ball = new Ball();
    return $ball;
}
</code></pre>
<p>As you can see, a static call to make creates a new instance of our class, and hands it back as the result. So this line of PHP is perfectly acceptable..</p>
<pre><code>$ball = Ball::make();
</code></pre>
<p>Similar to..</p>
<pre><code>$ball = new Ball();
</code></pre>
<p>Now we know what our creator method does, let&#8217;s have a closer look at the <code>chain</code> methods..</p>
<pre><code>// chain
public function size($size)
{
    $this-&gt;size = $size;
    return $this;
}

// chain
public function color($color)
{
    $this-&gt;color = $color;
    return $this;
}

// chain
public function texture($texture)
{
    $this-&gt;texture = $texture;
    return $this;
}
</code></pre>
<p>The chain methods are making changes to class attributes using the parameters provided to them, and returning the current object instance, which can always be found using <code>$this</code>.</p>
<p>So now we could use the following code..</p>
<pre><code>$ball = Ball::make();
$ball-&gt;color('red');
</code></pre>
<p>This is perfectly fine, but it could look better. The <code>make()</code> method is returning an object instance, so we can attach our chain method on to the end, to call the method on the object instance that has been returned. Therefore the code..</p>
<pre><code>$ball = Ball::make()-&gt;color('red');
</code></pre>
<p>Which will perform in the same way as the last code snippet. We can attach as many chains as we want, because they all return the current object instance, for example..</p>
<pre><code>$ball = Ball::make()-&gt;color('red')-&gt;size(5)-&gt;texture('fuzzy');
</code></pre>
<p>The chains can also be added in any order we like.</p>
<p>To make use of our changes we will need to use a <code>trigger</code> method, in our class the trigger method is <code>get()</code>.</p>
<pre><code>// trigger
public function get()
{
    return "This is a {$this-&gt;texture} {$this-&gt;color} ball, size {$this-&gt;size}.";
}
</code></pre>
<p>The <code>get()</code> method makes use of all our newly set class attributes and returns a short sentence describing the ball that we have made.</p>
<pre><code>echo Ball::make()-&gt;size(4)-&gt;get();
</code></pre>
<p>gives..</p>
<pre><code>This is a squishy blue ball, size 4.
</code></pre>
<p>In this example I have simply supplied the <code>size()</code> chain, which works fine because I have set default values for all my class attributes.</p>
<p>So now we know how to make a chainable class, and some &#8216;Laravelish&#8217; libraries, go forth and make clean, expressive bundles!</p>
]]></content:encoded>
			<wfw:commentRss>http://daylerees.com/2012/04/13/trick-chainable-libraries/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Trick: Psychic Controllers</title>
		<link>http://daylerees.com/2012/04/13/trick-psychic-controllers/</link>
		<comments>http://daylerees.com/2012/04/13/trick-psychic-controllers/#comments</comments>
		<pubDate>Fri, 13 Apr 2012 17:57:35 +0000</pubDate>
		<dc:creator>Dayle</dc:creator>
				<category><![CDATA[Laravel Tricks]]></category>

		<guid isPermaLink="false">http://daylerees.com/?p=217</guid>
		<description><![CDATA[Exciting! Who&#8217;s mind will we be reading today? Actually today Laravel will be reading your mind, and finding your controllers all on its own. By now you should be used to creating a Route stub for your controllers, something that looks a little bit like this.. Route::controller('controllername'); If you have progressed a little you may [...]]]></description>
			<content:encoded><![CDATA[<p>Exciting! Who&#8217;s mind will we be reading today? Actually today Laravel will be reading your mind, and finding your controllers all on its own.</p>
<p>By now you should be used to creating a Route stub for your controllers, something that looks a little bit like this..</p>
<pre><code>Route::controller('controllername');
</code></pre>
<p>If you have progressed a little you may even be passing an array to simplify the process. By creating the stubs you are letting Laravel know that the controller exists, and is routable, this enables a load of cool functionality powered by reverse routing.</p>
<p>However, if you have migrated from another well known framework (who&#8217;s name sounds like burning your source code) you may be familiar with URI&#8217;s such as..</p>
<pre><code>myapp.com/controller/action/param/param/param
</code></pre>
<p>In this case the first segment of the URL points to the controller in use, the second segment points to the controller action, and any additional segments are passed as parameters to the action. This is how &#8216;that other framework&#8217; handles it, and does not force you to register routes.</p>
<p>Well here&#8217;s a quick tip to force Laravel to route in a similar way, only reverse routing will still be available! Simply pass the <code>Controller::detect()</code> method to the <code>Route::controller()</code> method, for example..</p>
<pre><code>Route::controller(Controller::detect());
</code></pre>
<p>You see the <code>Controller::detect()</code> method will look at the filesystem, and detect all Controllers for the <code>DEFAULT_BUNDLE</code> which is our <code>application</code> folder. It will then return an array containing all the controllers it found. The <code>Route::controller()</code> method will then take that array, and register all of the controllers within the Routing engine, simple!</p>
<p>You can even pass a bundle name as a parameter to the <code>detect()</code> method to register all controllers for that bundle, for example..</p>
<pre><code>Route::controller(Controller::detect('mybundle'));
</code></pre>
<p>Enjoy using your psychic controllers!</p>
]]></content:encoded>
			<wfw:commentRss>http://daylerees.com/2012/04/13/trick-psychic-controllers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

