Brings back the helper classes and methods from Laravel 3 to Laravel 4... and all that in a single, convenient package!
laravel4-powerpack
contains Laravel 4 ports of the following helper classes:
Open up the Laravel 4 composer.json
file and add the laravelbook/laravel4-powerpack
package to the require
section:
{
"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:
$ composer update
You'll now have a composer.json
, composer.lock
as well as a vendor
folder which contains:
vendor/autoload.php
vendor/composer
vendor/laravel
vendor/laravelbook/laravel4-powerpack
...
The folder vendor/laravelbook/laravel4-powerpack
contain the Laravel 4 PowerPack components:
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:
$ 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:
"LaravelBook\Laravel4Powerpack\Providers\PowerpackServiceProvider",
The providers
section should look like the following snippet:
'providers' => array(
...
'LaravelBook\Laravel4Powerpack\Providers\PowerpackServiceProvider',
),
Next, add the following code to the aliases
array in the app/config/app.php
file:
'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:
'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!
You can verify the installation by running some simple test code like this:
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 );
});
- Entities
- Scripts And Style Sheets
- Links
- Links To Named Routes
- Links To Controller Actions
- Mail-To Links
- Images
- Lists
- Custom Macros
When displaying user input in your Views, it is important to convert all characters which have significance in HTML to their "entity" representation.
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:
echo HTML::entities('<script>alert(\'hi\');</script>');
echo HTML::script('js/scrollTo.js');
echo HTML::style('css/common.css');
echo HTML::style('css/common.css', array('media' => 'print'));
Further Reading:
echo HTML::link('user/profile', 'User Profile');
echo HTML::secure('user/profile', 'User Profile');
echo HTML::link('user/profile', 'User Profile', array('id' => 'profile_link'));
echo HTML::route('profile');
$url = HTML::route('profile', 'User Profile', array($username));
Further Reading:
echo HTML::action('home@index');
echo HTML::action('user@profile', 'User Profile', array($username));
The "mailto" method on the HTML class obfuscates the given e-mail address so it is not sniffed by bots.
echo HTML::mailto('example@gmail.com', 'E-Mail Me!');
echo HTML::mailto('example@gmail.com');
echo HTML::image('img/smile.jpg', $alt_text);
echo HTML::image('img/smile.jpg', $alt_text, array('id' => 'smile'));
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'));
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:
HTML::macro('myElement', function()
{
return '<article type="awesome">';
});
Now you can call your macro using its name:
echo HTML::myElement();
- Opening A Form
- CSRF Protection
- Labels
- Text, Text Area, Password & Hidden Fields
- File Input
- Checkboxes and Radio Buttons
- Drop-Down Lists
- Buttons
- Custom Macros
Note: All input data displayed in form elements is filtered through the HTML::entities method.
echo Form::open();
echo Form::open('user/profile', 'PUT');
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();
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:
Generating a hidden field containing the session's CSRF token:
echo Form::token();
Route::post('profile', array('before' => 'csrf', function()
{
//
}));
$token = Session::getToken();
Note: You must specify a session driver before using the Laravel CSRF protection facilities.
Further Reading:
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.
Text, Text Area, Password & Hidden Fields
echo Form::text('username');
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!
echo Form::password('password');
echo Form::checkbox('name', 'value');
echo Form::checkbox('name', 'value', true);
Note: The radio method has the same signature as the checkbox method. Two for one!
echo Form::file('image');
echo Form::select('size', array('L' => 'Large', 'S' => 'Small'));
echo Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S');
echo Form::submit('Click Me!');
Note: Need to create a button element? Try the button method. It has the same signature as submit.
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:
Form::macro('myField', function()
{
return '<input type="awesome">';
});
Now you can call your macro using its name:
echo Form::myField();
- Capitalization, Etc.
- Word & Character Limiting
- Generating Random Strings
- Singular & Plural
- Slugs
- Case Conversion
- String Searching
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:
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:
length( $string )
: Get the length of a string.
// 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.
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, '---');
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.
echo Str::random(32);
echo Str::random(32, 'alpha');
echo Str::plural('user');
// users
echo Str::singular('users');
// user
echo Str::plural('comment', count($comments));
return Str::slug('My First Blog Post!');
// my-first-blog-post
return Str::slug('My First Blog Post!', '_');
// my_first_blog_post
ascii( $value )
: Convert a string to 7-bit ASCII.
classify( $value )
: Convert a string to an underscored, camel-cased class name.
$class = Str::classify('task_name'); // Returns "Task_Name"
$class = Str::classify('taylor otwell') // Returns "Taylor_Otwell"
camelCase( $value )
: Convert a value to camel case.
is( $pattern, $value )
: Determine if a given string matches a given pattern.
endsWith( $haystack, $needle )
: Determine if a given string ends with a given needle.
startsWith( $haystack, $needle )
: Determine if a string starts with a given needle.
contains( $haystack, $needle )
: Determine if a given string contains a given sub-string.
dd( $value )
: Dumps the given value. Execution will halt after call to this function.