In this article, I will take a look at the new features of Laravel 5.2 and describe them one by one. The new features are listed below:
- implicit route model binding
- form array validation
- API rate-limiting middleware
- middleware groups
- authentication scaffold
- multiple authentication guard drivers
Multiple Authentication Guard Drivers
This feature will help you, especially when you need to have Doctrine ORM Auth with multiple providers. In my projects I prefer to have admin and user authentication separate from each other; this feature will help me to achieve this easily. Let see an example config/auth.php
:
//... 'guards' => [ 'user' => [ 'driver' => 'session', 'provider' => 'users', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admin', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], ], //... 'providers' => [ 'users' => [ 'driver' => 'doctrine', 'model' => App\Entities\Users::class, ], 'admin' => [ 'driver' => 'doctrine', 'model' => App\Entities\Admin::class, ], ],
Now, when you use Auth::attempt([...])
, Laravel will call the default guard; so if you want to use a specific guard, just call with its name, such as Auth::guard('admin')
.
For authentication in your route group with a specific guard, you can just call the guard name:
Route::group(['middleware' =>['auth:admin']], function () { //... }
Sometimes, rather than a simple login in your app, you wish users to append an api_token
to the end of their query string and use that to authenticate their request. The TokenGuard will let you achieve this easily.
If you want to use token authentication, first of all you need to add a 60-character unique api_token
field into the database table of the selected model (entity in doctrine). Now you can easily use api
guard in your app.
Implicit Route Model Binding
One of the new features of Laravel 5.2 that's very practical is route model binding. You can bind the model to your route; before this we would create it manually:
Route::get('user/{id}', function ($id) { $user = Users::findOrFail($id); // ... });
Or you may do something like:
//... $router->model('user', 'App\User'); //... $router->get('profile/{user}', function(App\User $user) { // });
Laravel 5.2 makes it even easier. Just pass a parameter in the route closure, and it'll automatically treat it as a route model binding:
Route::get('user/{id}', function (App\User $user) { //... });
Now it is easier to bind the model to your route.
By default, Laravel uses the model's id column. But if you expect it to change the mapping, you may change your model like so:
class User extends Model { public function getRouteKeyName() { return 'UserEmail'; } }
Eloquent implements the Illuminate\Contracts\Routing\UrlRoutable
contract, so you can override the getRouteKeyName()
method. It defines which column should be used to look it up from a URL.
Middleware Groups
As you can see in the above section, we have created a different guard for user and admin. In this case, if you want to assign multiple middleware to a user route group or your admin route group, Laravel 5.2 lets you create a shortcut with a key name.
In order to define the middleware group, you should modify the kernel.php in your http folder:
protected $middlewareGroups = [ //... 'admin' => [ 'acl', 'web', 'auth', ] ];
And now you can easily use it in your route group.
Api Rate-Limiting Middleware
If you use the API of another application like GitHub, for requests using Basic Authentication or OAuth, you can make up to 5,000 requests per hour. This limitation is called rate limiting. If you want to have something like this in your app, you may use Laravel 5.2's new feature. Laravel 5.2 added new throttle
middleware that will handle rate limiting. For example, you may have something like:
Route::group(['prefix' => 'api', 'middleware' => 'throttle'], function () { Route::get('user', function () { return Users::all(); }); });
By default, throttle
middleware allows 60 attempts per minute in kernel.php
:
//... 'api' => [ 'throttle:60,1', 'auth:api', ],
You may change it as you want or even customize it for a specific router:
Route::group(['prefix' => 'api', 'middleware' => 'throttle:10,1000'], function () { Route::get('user', function () { return Users::all(); }); });
Authentication Scaffold
Laravel 5.2 provides a quick way to scaffold everything you need for authentication using this command:
php artisan make:auth
Using this command in your new application will make registration and login views, as well as routes for all authentications. My route file looks like:
Route::group(['middleware' => 'web'], function () { Route::auth(); Route::get('/home', 'HomeController@index'); });
The Route::auth()
method is a shortcut to defining the following routes:
// Authentication Routes... $this->get('login', 'Auth\AuthController@showLoginForm'); $this->post('login', 'Auth\AuthController@login'); $this->get('logout', 'Auth\AuthController@logout'); // Registration Routes... $this->get('register', 'Auth\AuthController@showRegistrationForm'); $this->post('register', 'Auth\AuthController@register'); // Password Reset Routes... $this->get('password/reset/{token?}', 'Auth\PasswordController@showResetForm'); $this->post('password/email', 'Auth\PasswordController@sendResetLinkEmail'); $this->post('password/reset', 'Auth\PasswordController@reset');
A HomeController
will also be generated, which is responsible for login requests to your application's dashboard. But you can customize or remove this controller based on the needs of your application.
Form Array Validation
One of the interesting things I have worked with is array form data in HTML. If you place something within the square brackets then the resulting array becomes associative; otherwise, it’ll be numeric:
<form action="" method="POST"> <input type="text" name="name[first]"> <input type="text" name="name[last]"> <input type="submit"> </form>
The PHP print_r($_POST)
result will be:
array( 'name' => array( 'first' => '' 'last' => '' ) )
This will help you to simplify the process of validation and working with forms. Now let's see validation for our user fields in Laravel 5.2:
public function Validator() { $this->validate(Request::all(), [ 'name.*.first' => 'required|string', 'name.*.last' => 'string', ]); }
You may have noticed that the shape of the validation is name.*.last
, with an asterisk in the middle, which almost indicates that you could add the key of an array or anything else you may need.
Conclusion
Laravel 5.2 was a small release that may let you work better and quicker. As you may notice, many of these features are also easy to learn.
Comments