laravel4-powerpack
Brings back the helper classes and methods from Laravel 3 to Laravel 4... and all that in a single, convenient package!, (*1)
, (*2)
laravel4-powerpack contains Laravel 4 ports of the following helper classes:, (*3)
Installation
Open up the Laravel 4 composer.json file and add the laravelbook/laravel4-powerpack package to the require section:, (*7)
{
"require": {
"laravel/framework": "4.0.*",
...
"laravelbook/laravel4-powerpack": "dev-master"
}
...
}
Run the composer install or update task, which will make composer download requested packages and setup initial environment:, (*8)
$ composer update
You'll now have a composer.json, composer.lock as well as a vendor folder which contains:, (*9)
vendor/autoload.php
vendor/composer
vendor/laravel
vendor/laravelbook/laravel4-powerpack
...
The folder vendor/laravelbook/laravel4-powerpack contain the Laravel 4 PowerPack components:, (*10)
vendor/laravelbook/laravel4-powerpack/src/LaravelBook/Laravel4Powerpack/HTML.php
vendor/laravelbook/laravel4-powerpack/src/LaravelBook/Laravel4Powerpack/Form.php
vendor/laravelbook/laravel4-powerpack/src/LaravelBook/Laravel4Powerpack/Str.php
By default, composer will autoload the required classes. If you encounter any error, run the following command to force composer re-generate the autoload file:, (*11)
$ composer dump-autoload
Next, we need to install the package in your Laravel 4 application. Open up the the app/config/app.php file and append the following code to the providers array:, (*12)
"LaravelBook\Laravel4Powerpack\Providers\PowerpackServiceProvider",
The providers section should look like the following snippet:, (*13)
'providers' => array(
...
'LaravelBook\Laravel4Powerpack\Providers\PowerpackServiceProvider',
),
Next, add the following code to the aliases array in the app/config/app.php file:, (*14)
'HTML' => 'LaravelBook\Laravel4Powerpack\Facades\HTMLFacade',
'Form' => 'LaravelBook\Laravel4Powerpack\Facades\FormFacade',
'Str' => 'LaravelBook\Laravel4Powerpack\Facades\StrFacade',
The aliases array should now look like the snippet below:, (*15)
'aliases' => array(
...
'HTML' => 'LaravelBook\Laravel4Powerpack\Facades\HTMLFacade',
'Form' => 'LaravelBook\Laravel4Powerpack\Facades\FormFacade',
'Str' => 'LaravelBook\Laravel4Powerpack\Facades\StrFacade',
),
Laravel 4 Powerpack is now ready to be used in your web application!, (*16)
You can verify the installation by running some simple test code like this:, (*17)
Route::get('/', function() {
echo Form::open( '/' );
echo HTML::image( 'img/hello.jpg' );
echo Form::text( Str::upper('hello world!') );
echo Form::close();
echo dd( $_REQUEST );
});
, (*18)
Building HTML
Content
, (*19)
Entities
When displaying user input in your Views, it is important to convert all characters which have significance in HTML to their "entity" representation., (*20)
For example, the < symbol should be converted to its entity representation. Converting HTML characters to their entity representation helps protect your application from cross-site scripting:, (*21)
Converting a string to its entity representation:
echo HTML::entities('');
, (*22)
Scripts And Style Sheets
Generating a reference to a JavaScript file:
echo HTML::script('js/scrollTo.js');
Generating a reference to a CSS file:
echo HTML::style('css/common.css');
echo HTML::style('css/common.css', array('media' => 'print'));
Further Reading:, (*23)
, (*24)
Links
Generating a link from a URI:
echo HTML::link('user/profile', 'User Profile');
Generating a link that should use HTTPS:
echo HTML::secure('user/profile', 'User Profile');
Generating a link and specifying extra HTML attributes:
echo HTML::link('user/profile', 'User Profile', array('id' => 'profile_link'));
, (*25)
Links To Named Routes
Generating a link to a named route:
echo HTML::route('profile');
Generating a link to a named route with wildcard values:
$url = HTML::route('profile', 'User Profile', array($username));
Further Reading:, (*26)
, (*27)
Links To Controller Actions
Generating a link to a controller action:
echo HTML::action('home@index');
Generating a link to a controller action with wildcard values:
echo HTML::action('user@profile', 'User Profile', array($username));
, (*28)
Mail-To Links
The "mailto" method on the HTML class obfuscates the given e-mail address so it is not sniffed by bots., (*29)
Creating a mail-to link:
echo HTML::mailto('example@gmail.com', 'E-Mail Me!');
Creating a mail-to link using the e-mail address as the link text:
echo HTML::mailto('example@gmail.com');
, (*30)
Images
Generating an HTML image tag:
echo HTML::image('img/smile.jpg', $alt_text);
echo HTML::image('img/smile.jpg', $alt_text, array('id' => 'smile'));
, (*31)
Lists
Creating lists from an array of items:
echo HTML::ol(array('Get Peanut Butter', 'Get Chocolate', 'Feast'));
echo HTML::ul(array('Ubuntu', 'Snow Leopard', 'Windows'));
echo HTML::dl(array('Ubuntu' => 'Canonical', 'Windows' => 'Microsoft'));
, (*32)
Custom Macros
It's easy to define your own custom HTML class helpers called "macros". Here's how it works. First, simply register the macro with a given name and a Closure:, (*33)
Registering a HTML macro:
HTML::macro('myElement', function()
{
return '<article type="awesome">';
});
Now you can call your macro using its name:, (*34)
Calling a custom HTML macro:
echo HTML::myElement();
, (*35)
Contents
Note: All input data displayed in form elements is filtered through the HTML::entities method., (*36)
, (*37)
Opening a form to POST to the current URL:
echo Form::open();
echo Form::open('user/profile', 'PUT');
Opening a Form that POSTS to a HTTPS URL:
echo Form::openSecure('user/profile');
echo Form::open('user/profile', 'POST', array('class' => 'awesome'));
echo Form::openForFiles('users/profile');
echo Form::openSecureForFiles('users/profile');
echo Form::close();
, (*38)
CSRF Protection
Laravel provides an easy method of protecting your application from cross-site request forgeries. First, a random token is placed in your user's session. Don't sweat it, this is done automatically. Next, use the token method to generate a hidden form input field containing the random token on your form:, (*39)
Generating a hidden field containing the session's CSRF token:
echo Form::token();
Attaching the CSRF filter to a route:
Route::post('profile', array('before' => 'csrf', function()
{
//
}));
Retrieving the CSRF token string:
$token = Session::getToken();
Note: You must specify a session driver before using the Laravel CSRF protection facilities., (*40)
Further Reading:, (*41)
, (*42)
Labels
Generating a label element:
echo Form::label('email', 'E-Mail Address');
echo Form::label('email', 'E-Mail Address', array('class' => 'awesome'));
Note: After creating a label, any form element you create with a name matching the label name will automatically receive an ID matching the label name as well., (*43)
, (*44)
Text, Text Area, Password & Hidden Fields
Generate a text input element:
echo Form::text('username');
Specifying a default value for a text input element:
echo Form::text('email', 'example@gmail.com');
Note: The hidden and textarea methods have the same signature as the text method. You just learned three methods for the price of one!, (*45)
echo Form::password('password');
, (*46)
echo Form::checkbox('name', 'value');
Generating a checkbox that is checked by default:
echo Form::checkbox('name', 'value', true);
Note: The radio method has the same signature as the checkbox method. Two for one!, (*47)
, (*48)
echo Form::file('image');
, (*49)
Drop-Down Lists
Generating a drop-down list from an array of items:
echo Form::select('size', array('L' => 'Large', 'S' => 'Small'));
Generating a drop-down list with an item selected by default:
echo Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S');
, (*50)
echo Form::submit('Click Me!');
Note: Need to create a button element? Try the button method. It has the same signature as submit., (*51)
, (*52)
Custom Macros
It's easy to define your own custom Form class helpers called "macros". Here's how it works. First, simply register the macro with a given name and a Closure:, (*53)
Form::macro('myField', function()
{
return '<input type="awesome">';
});
Now you can call your macro using its name:, (*54)
echo Form::myField();
, (*55)
Working With Strings
Contents
, (*56)
Capitalization, Etc.
The Str class provides three convenient methods for manipulating string capitalization: upper, lower, and title. These are more intelligent versions of the PHP strtoupper, strtolower, and ucwords methods. More intelligent because they can handle UTF-8 input if the multi-byte string PHP extension is installed on your web server. To use them, just pass a string to the method:, (*57)
echo Str::lower('I am a string.');
// i am a string.
echo Str::upper('I am a string.');
// I AM A STRING.
echo Str::title('I am a string.');
// I Am A String.
Additional methods:, (*58)
length( $string ): Get the length of a string., (*59)
// Get the length of a string
$length = Str::length('Taylor Otwell');
// Get the length of a multi-byte string
$length = Str::length('Τάχιστη')
upperWords( $string ): Convert first letter of each word to uppercase., (*60)
, (*61)
Word & Character Limiting
Limiting the number of characters in a string:
echo Str::limit("Lorem ipsum dolor sit amet", 10);
// Lorem ipsu...
echo Str::limitExact("Lorem ipsum dolor sit amet", 10);
// Lorem i...
// Limit the number of characters and append a custom ending
echo Str::limitExact('Taylor Otwell', 9, '---');
Limiting the number of words in a string:
echo Str::words("Lorem ipsum dolor sit amet", 3);
// Lorem ipsum dolor...
// Limit the number of words and append a custom ending
echo Str::words('This is a sentence.', 3, '---');
wordwrap( $string, $length ): Adds a space to a string after a given amount of contiguous, non-whitespace characters., (*62)
, (*63)
Generating Random Strings
Generating a random string of alpha-numeric characters:
echo Str::random(32);
Generating a random string of alphabetic characters:
echo Str::random(32, 'alpha');
, (*64)
Singular & Plural
echo Str::plural('user');
// users
echo Str::singular('users');
// user
echo Str::plural('comment', count($comments));
, (*65)
Slugs
Generating a URL friendly slug:
return Str::slug('My First Blog Post!');
// my-first-blog-post
Generating a URL friendly slug using a given separator:
return Str::slug('My First Blog Post!', '_');
// my_first_blog_post
, (*66)
Case Conversion
ascii( $value ): Convert a string to 7-bit ASCII., (*67)
classify( $value ): Convert a string to an underscored, camel-cased class name., (*68)
$class = Str::classify('task_name'); // Returns "Task_Name"
$class = Str::classify('taylor otwell') // Returns "Taylor_Otwell"
camelCase( $value ): Convert a value to camel case., (*69)
, (*70)
String Searching
is( $pattern, $value ): Determine if a given string matches a given pattern., (*71)
endsWith( $haystack, $needle ): Determine if a given string ends with a given needle., (*72)
startsWith( $haystack, $needle ): Determine if a string starts with a given needle., (*73)
contains( $haystack, $needle ): Determine if a given string contains a given sub-string., (*74)
Additional Helper Methods
dd( $value ): Dumps the given value. Execution will halt after call to this function., (*75)