Laravel - Localization and Session Management
This article will continue where we left off in Part 4 of the Laravel tutorial series. Laravel is a powerful MVC PHP framework, designed for developers who need a simple and elegant toolkit to create full-featured web applications. Laravel was created by Taylor Otwell.
In this article, we will have a look at form handling, implementing localization, managing sessions, validating inputs and uploading files in the framework. So, let’s dive straight into the code.
Localization
The Laravel Lang class provides a convenient way of retrieving strings in various languages, allowing you to easily support multiple languages within our application.
Language Files
Language strings are stored in files within the app/lang directory. Within this directory there should be a subdirectory for each language we want to support in the application.
/app
/lang
/en
messages.php
/es
messages.php
Example Language File
Language files simply return an array of keyed strings. For instance:
<?php
return array(
'welcome' => 'Welcome to our application'
);
Changing The Default Language At Runtime
The default language for the app is stored in the app/config/app.php configuration file. We may change the active language at any time using the App::setLocale method:
App::setLocale('es');
Setting The Fallback Language
We can also configure a "fallback language", which will be used when the active language does not contain a given language line. Like the default language, the fallback language is also configured in the app/config/app.php configuration file:
'fallback_locale' => 'en',
Basic Usage
Retrieving Lines From A Language File
echo Lang::get('messages.welcome');
The first segment of the string passed to the get method is the name of the language file, and the second is the name of the line that should be retrieved.
Note: If a language line does not exist, the key will be returned by the get method.
You may also use the trans helper function, which is an alias for the Lang::get method.
echo trans('messages.welcome');
Making Replacements In Lines
We can also define placeholders in our language lines:
'welcome' => 'Welcome, :name',
Then, pass a second argument of replacements to the Lang::get method:
echo Lang::get('messages.welcome', array('name' => 'Dayle'));
Determine If A Language File Contains A Line
if (Lang::has('messages.welcome'))
{
//
}
Pluralization
Pluralization is a complex problem, as different languages have a variety of complex rules for pluralization. We can easily manage this in our language files. By using a "pipe" character, we may separate the singular and plural forms of a string:
'apples' => 'There is one apple|There are many apples',
We can then use the Lang::choice method to retrieve the line:
echo Lang::choice('messages.apples', 10);
We can also supply a locale argument to specify the language. For example, if we want to use the Russian (ru) language:
echo Lang::choice('товар|товара|товаров', $count, array(), 'ru');
Since the Laravel translator is powered by the Symfony Translation component, you may also create more explicit pluralization rules easily:
'apples' => '{0} There are none|[1,19] There are some|[20,Inf] There are many',
Validation
For localization for validation errors and messages, take a look at the documentation on Validation.
Overriding Package Language Files
Many packages ship with their own language lines. Instead of hacking the package's core files to tweak these lines, we may override them by placing files in the app/lang/packages/{locale}/{package} directory.
So, for instance, when we need to override the English language lines in messages.php for a package named skyrim/hearthfire, we would place a language file at: app/lang/packages/en/hearthfire/messages.php.
In this file we would define only the language lines we wish to override. Any language lines we don't override will still be loaded from the package's language files.
Session Management
As we know that HTTP apps are stateless, sessions provide a way to store information about the user across requests. Laravel ships with a variety of session backends available for use through a neat, unified API. Support for popular back-ends such as Memcached, Redis, and databases are already included.
The session configuration is stored in app/config/session.php.
>>> By default, Laravel is configured to use the filesession driver, which will work well for the majority of applications.
Reserved Keys
The Laravel framework uses the flash session key internally, so we should not add an item to the session by that name.
Session Usage
Storing An Item In The Session
Session::put('key', 'value');
Push A Value Onto An Array Session Value
Session::push('user.profession', 'developers');
Retrieving An Item From The Session
$value = Session::get('key');
Retrieving An Item Or Returning A Default Value
$value = Session::get('key', 'default');
$value = Session::get('key', function() { return 'default'; });
Retrieving An Item And Forgetting It
$value = Session::pull('key', 'default');
Retrieving All Data From The Session
$data = Session::all();
Determining If An Item Exists In The Session
if (Session::has('developers'))
{
//
}
Removing An Item From The Session
Session::forget('key');
Removing All Items From The Session
Session::flush();
Regenerating The Session ID
Session::regenerate();
Flash Data
Sometimes you may wish to store items in the session only for the next request. You may do so using the Session::flash method:
Session::flash('key', 'value');
Reflashing The Current Flash Data For Another Request
Session::reflash();
Reflashing Only A Subset Of Flash Data
Session::keep(array(email, hello@discoversdk.com));
Session Drivers
The session "driver" defines where session data will be stored for each request. Laravel ships with many good drivers like:
- file - sessions will be stored in app/storage/sessions.
- cookie - sessions will be stored in secure, encrypted cookies.
- database - sessions will be stored in a database used by our application.
- memcached / redis - sessions will be stored in one of these fast, cached based stores.
- array - sessions will be stored in a simple PHP array and will not be persisted across requests.
Validation
Laravel comes with a very clean, easy to use facility for validating data and retrieving validation error messages via the Validation class.
Basic Validation Example
$validator = Validator::make(
array('name' => 'Shubham'),
array('name' => 'required|min:5')
);
The first argument passed to the make method is the data under validation. The second argument is the validation rules that should be applied to the data.
Using Arrays To Specify Rules
Multiple rules may be delimited using either a "pipe" character, or as separate elements of an array.
$validator = Validator::make(
array('name' => 'Shubham'),
array('name' => array('required', 'min:5'))
);
Validating Multiple Fields
$validator = Validator::make(
array(
'name' => 'Shubham',
'password' => 'lamepassword',
'email' => 'email@example.com'
),
array(
'name' => 'required',
'password' => 'required|min:8',
'email' => 'required|email|unique:users'
)
);
Once a Validator instance has been created, the fails (or passes) method can be used to do the validation.
if ($validator->fails())
{
// The given data did not pass validation
}
If validation has failed, we can obtain the error messages from the validator.
$messages = $validator->messages();
We can also access an array of the failed validation rules, without messages. To do so, let’s use the failed method:
$failed = $validator->failed();
Validating Files
The Validator class provides several rules for validating files, such as size, mimes, and others. When validating files, you may simply pass them into the validator with your other data.
Working With Error Messages
After calling the messages method on a Validator instance, we will receive a MessageBaginstance, which has a variety of convenient methods for working with error messages.
Retrieving The First Error Message For A Field
echo $messages->first('email');
Retrieving All Error Messages For A Field
foreach ($messages->get('email') as $message)
{
//
}
Retrieving All Error Messages For All Fields
foreach ($messages->all() as $message)
{
//
}
Determining If Messages Exist For A Field
if ($messages->has('email'))
{
//
}
Retrieving An Error Message With A Format
echo $messages->first('email', '<p>:message</p>');
Note: By default, messages are formatted using Bootstrap compatible syntax.
Retrieving All Error Messages With A Format
foreach ($messages->all('<li>:message</li>') as $message)
{
//
}
Error Messages & Views
Once we are done with validation, we will need a clean way to get the error messages back to our views. This is easily managed by Laravel. Consider the following routes as an example:
Route::get('register', function()
{
return View::make('user.register');
});
Route::post('register', function()
{
$rules = array(...);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to('register')->withErrors($validator);
}
});
Note that when validation fails, we pass the Validator instance to the Redirect using the withErrors method. This method will flash the error messages to the session so that they are available on the next request.
So, after redirection, we can use the automatically bound $errors variable in our view:
<?php echo $errors->first('email'); ?>
Named Error Bags
If we have multiple forms on a single page, we can wish to name the MessageBag of errors. This will allow us to retrieve the error messages for a specific form. Simply pass a name as the second argument to withErrors:
return Redirect::to('register')->withErrors($validator, 'login');
We can then access the named MessageBag instance from the $errors variable:
<?php echo $errors->login->first('email'); ?>
Conclusion
In this article, we studied form handling, implementing localization, managing sessions, validating inputs and uploading files in Laravel.
There is a lot more to come which we will read in the Part 6 of our Laravel tutorial series which will cover Ajax handling and Security in Laravel. Stay tuned for more!
Recent Stories
Compare Products
Select up to three two products to compare by clicking on the compare icon () of each product.
{{compareToolModel.Error}}
{{CommentsModel.TotalCount}} Comments
Your Comment