
Even though we were planned to give a blog on “The features of AWS in a Nutshell” as Laravel 5.2 got released my team decided to first give a clear view to readers on this that is the reason we have this blog.
We will have a glance of some of the features which we need to know in Larval 5.2. Release
1. Array Validation
In the previous version of Laravel, we need to loop through the array variables and do the validation like the below example
Example :
In view file which is common to 5.1 and 5.2
<input type=’text’ class=’form-control required’ name=’fields[1]’>
<input type=’text’ class=’form-control required’ name=’fields[2]’>
<input type=’text’ class=’form-control required’ name=’fields[3]’>
Validation in Request upto Larvel 5.1
public function rules() {
foreach ($this->request->get(‘fields’) as $key => $val) {
$rules[‘fields.’ . $key] = ‘required|string’;
}
return $rules;
}
But now in Laravel 5.2, this has been simplified as below and it is much easier to as like other validations.
Example :
public function store(Request $request) {
$this->validate($request->all(), [
‘fields.*’ => ‘required|string’>
]);
}
2. API Rate Limiting
First let’s explain what is rate limiting – It allows to limit the number of requests that a given IP address can make to a route over a specified number of minutes.
For example, to limit a route with only 30 requests per minute from a single IP address, it can be achieved by following
Example :
Route::get(‘/api/orders’, [‘middleware’ => ‘throttle:30,1’, function () {
return Order::all();
}]);
3. Auth Scaffolding
In previous versions, if we need to have view files for authentication purposes, we specifically need to include the package.
But now in this latest version, we just have the files for views in front-end by simply executing the make:auth command.
Example :
php artisan make:auth
4. Appending output from scheduled tasks
Previously, Laravel included a sendOutputTo option to write the current results of scheduled job. It overwrites every time the scheduler task runs.
But now the result of the tasks can be appended to the same file by using ‘appendOutputTo’.
Example :
$schedule->command(’emails:send’)
->hourly()
->appendOutputTo($filePath);
5. Implicit route model binding
Implicit model binding is newly added feature in this version which is for binding a model to route.
Example :
Route::get(‘items/{item}’, function(Item $item) {
return $item;
});
Here, Item::findOrFail($item) will be executed by default and will return the result in $item variable. The item parameter will be automatically bind to Item model.
In previous version, we need to do this model binding in RouteServiceProvider::boot method by manually as below.
Example :
Binding A Parameter To A Model
public function boot(Router $router) {
parent::boot($router);
$router->model(‘item’, ‘AppItem’);
}
6. Collections Wildcards
If you want to pull out data while using a collection, it is now easy by passing a (*) as a wildcard.
Example :
$posts->pluck(‘events.*.title’);
This will return all event’s title.
7. Global Scopes
Eloquent Global Scopes:
Global scopes will allow us to use some common type of constraints in all the eloquent queries as like soft delete concept. Now this feature becomes very simple than earlier.
You just need to create the scope class in the scopes directory which is not available in Laravel by default. You can create this directory by your own inside the app directory. And add the apply method in this class as below. Here you are allowed to add your own constraints.
Example :
<?php
namespace AppScopes;
use IlluminateDatabaseEloquentScope;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentBuilder;
class UserScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
* @param IlluminateDatabase EloquentBuilder $builder
* @param IlluminateDatabase EloquentModel $model
* @return void
*/
public function apply(Builder $builder, Model $model) {
return $builder->where(’status’, ‘=‘, 1);
}
}
You can easily apply this scope to your model by specifying the boot() method in your User model.
protected static function boot() {
parent::boot();
static::addGlobalScope(new UserScope);
}
Once you add this scope, you will be getting only the users whose status is 1 while you running User::all() query.
8. Middleware Groups
In the previous version, we can have only individual middleware routes, whereas now, we can group many classes as a separate middleware groups and used in routes.
Example :
protected $middlewareGroups = [
‘web’ => [
AppHttpMiddleware EncryptCookies::class,
IlluminateCookieMiddleware AddQueuedCookiesToResponse::class,
IlluminateSessionMiddleware StartSession::class,
IlluminateViewMiddleware ShareErrorsFromSession::class,
AppHttpMiddleware VerifyCsrfToken::class,
],
‘api’ => [
‘throttle:60,1’,
],
];
As per the above example, we can have separate middleware groups for web and API usage.
Example :
protected $middlewareGroups = [
‘web’ => […],
‘api’ => […],
‘admin’ => [
‘web’,
‘auth’,
]
];
Like the above code, we are allowed to group the group into another group, like admin can have access to all the routes inside that.