Exclusive Features in Laravel 5.2

  • Cubettech
  • Laravel Development
  • 8 years ago
Exclusive Features in Laravel 5.2

Now a days Laravel is the most admired PHP framework that assures rapid application development with tested functionality. Laravel has released its new version, Laravel 5.2 with features that are not covered in its previous versions. Let’s discuss about the key features of Laravel 5.2.

Key Features of Laravel 5.2

  1. Authentication Scaffolding
  2. Authentication Drivers / “Multi-Auth”
  3. Array Validation
  4. Middleware Groups
  5. Implicit Model Binding
  6. Rate Limiting
  7. Eloquent Global Scope Improvements
  8. Support for json data type
  9. Collections Wildcards
  10. Database Session Driver

1.Authentication Scaffolding

Authentication scaffolding is an best feature in Laravel 5.2 which creates auth views and routes with Bootstrap Layout format. You can make it with easy artisan command from your project root folder via terminal.

php artisan make:auth

The generated views are in bootstrap compatible format and it covers routes and view files for authentication, registration, and password resets. Following view files generated when we done authentication scaffold.

  • welcome.blade.php – the public welcome page
  • home.blade.php – the dashboard for logged-in users
  • auth/login.blade.php – the login page
  • auth/register.blade.php – the register/signup page
  • auth/passwords/email.blade.php – the password reset confirmation page
  • auth/passwords/reset.blade.php – the password reset prompt page
  • auth/emails/password.blade.php – the password reset email

The guest/public page is routed via routes.php

Route::get('/', function () {
    return view('welcome');
});

And now we got a HomeController, which routes our dashboard after login:

class HomeController extends Controller
{
    /**
    * Show the application dashboard.
    *
     * @return Response
    */
    public function index()
   {
       return view('home');
   }
}

The new entries on our routes.php after the scaffolding are look like following:

Route::group(['middleware' => 'web'], function () {
    Route::auth();
    Route::get('/home', 'HomeController@index');
});

In the above routing Route::auth() method implements the following route actions automatically.

// 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');

So this feature allows you to use all the above routes into a single line.

2. Authentication Drivers / “Multi-Auth”

Authentication drivers are used to authenticate users within the application. In previous releases, they only support authentication mechanisms which are based on session.

If you check config/auth.php file you can see two guards set: web, which is the classic Laravel authentication layer, and api, which is a stateless (no session memory) token-based driver.

  'guards' => [
       'web' => [
           'driver' => 'session',
           'provider' => 'users',
       ],

       'api' => [
           'driver' => 'token',
           'provider' => 'users',
       ],
   ],
Token Authentication Driver for Apis:-

Laravel 5.2 uses a stateless (no session memory) token-based driver to authenticate api requests. To implement token based authentication you need to do following actions.

    1. To start with, you need to  add an api_token column to your users table.
    2. Second, ensure that any routes that utilize Token Authentication are protected by the auth:api middleware. You can rely on the route group listed below as an example of what pertinent routes might look like.
      Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
              Route::post('/user/add, 'UsersController@store');
         });
    3. To get the authenticated user for this API request, use following snippet:
      Auth::guard('api')->user();
    4. In App\Http\Middleware\Authenticate middleware, you have to change the following lines:

      // Original
              if ($request->ajax()) {
                  return response('Unauthorized.', 401);
              } else {
                  return redirect()->guest('login');
             }
      
          // Updated
              if ($request->ajax() || $request->wantsJson()) {
                  return response('Unauthorized.', 401);
              } else {
                  return redirect()->guest('login');
              }

This will return a 401 status code to unauthorized API requests instead of redirect it to a login page.

3. Array Validation

Array validation of form inputs is far easier in Laravel 5.2 with an asterisk in the middle: employee.*.name

Consider a form that offers the privilege to add a company and the number of employees in the company as required. The form can also be populated with the entries: Employee Name and Title.

One of the solutions to add these employees is by relying on an “Add More” button powered by Javascript. However, the process of validating respective fields from the frontend can turn out to be hectic.

Laravel 5.2 made it easy with array validation. If we need to validate employee name, the following snippet is an example of validation.

// CompaniesController.php
   public function store(Request $request)
   {
       $this->validate($request->all(), [
           'name' => 'required|string'
       ]);
      // Save, etc.
   }

If you need to validate every employee[*][name] and employee[*][title] uniquely:

// CompaniesController.php
   public function store(Request $request)
   {
       $this->validate($request->all(), [
           'name' => 'required|string',
           'employee.*.name' => 'required|string',
           'employee.*.title' => 'string',
       ]);
      // Save, etc.
   }

4. Middleware Groups

Middleware Groups provides you with the provision of binding a single key with many route middlewares, i.e when you build an application based on API and UI.  

For the cause, you need to bind cookie, session, encrypted cookie or CSRF middleware under web key and bind throttling, API custom middlewares or request loggings under api key.

You can define middleware groups in app\Http\Kernel.php. There’s a new property named $middlewareGroups that’s an array; each key is a name and each value is the corresponding middleware.

protected $middlewareGroups = [
   'web' => [
       \App\Http\Middleware\EncryptCookies::class,
       \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
       \Illuminate\Session\Middleware\StartSession::class,
       \Illuminate\View\Middleware\ShareErrorsFromSession::class,
       \App\Http\Middleware\VerifyCsrfToken::class,
   ],

   'api' => [
       'throttle:60,1',
   ],
];

You can make custom middleware groups such as admin etc. as per the usage of the application.

5. Implicit Model Binding

In Laravel 5.2, as a developer, you would find the task of gaining access to the Model Instance a thorny one. In previous versions of Laravel needed Route::model method or App\User route URI instance as type-hinting, and Laravel would automatically inject the model instance that has an ID matching to the corresponding value from the request URI. The following routes depicts the Model binding on old Laravel versions and version 5.2.

In older Versions

Route::get(users/{id}', function ($id) {
   $user = User::findOrFail($id);
  // Do stuff
});

Laravel 5.2

use App\User;

Route::get('users/{user}', function ( User $user) {
  // Do stuff
});

6. Rate Limiting

Rate limiting is used in web applications to block/control the rate of traffic or continuous requests from some IP within the time interval to some route especially on API requests. Laravel 5.2 has in-built rate limiting support via middlewares. It depicts in following code snippet:

Route::group(['prefix' => 'api', 'middleware' => 'throttle:60,1'], function () {
   Route::get(‘users’, function () {
       return User::all();
   });
});

The above snippet limits the requests per minute from same ip to 60.

If limit exceeds 60 the response has the following header

HTTP/1.1 429 Too Many Requests
… other headers here …
Retry-After: 60
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0

If we retried after 30 seconds the header will

HTTP/1.1 429 Too Many Requests
… other headers here …
Retry-After: 30
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0

7. Eloquent Global Scope Improvements

Global Scopes are the constraints given to any Model so that all the queries of that model can use the applied constraints by default.

For example, you have database table users with a column, “age” and you need to display or work with the user’s age above 20.

Then you have to add a “where” clause in each query you declare like

select name, age, id from users where age > 20

Here is the global scopes come into play. Laravel 5.2 global query scopes only require you to implement a single, simple method: apply. Writing a global scope is simple.

You need to initially define a class that illuminate\Database\Eloquent\Scope interface. This interface requires you to implement one method: apply. To use global scopes you need to create Scopes directory into the app directory. In Scopes directory you need to create a file AgeScope.php with the following content:

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\Builder;

class AgeScope implements Scope

{

public function apply(Builder $builder, Model $model)

{

return $builder->where(‘age’, ‘>’, 20);

}

}

To assign a global scope to a model, you should override a given model’s boot method and use the addGlobalScope method:

<?php namespace App;

use App\Scopes\AgeScope;

use Illuminate\Database\Eloquent\Model;

class User extends Model

{

/**

* Initialise

*

* @return void

*/

protected static function boot()

{

    parent::boot();

static addGlobalScope(new AgeScope);

}

}

8. Support for json data type

In MySQL 5.7.8 added support for a native JSON data type. Laravel 5.2 now adds support for this column type.

9. Collections Wildcards

When using a collection and wanting to pull out data, you can now pass a * as a wildcard:

$posts->pluck(‘posts.*.title’);

This will return all title’s for all posts.

10. Database Session Driver

The database session driver now includes user_id and ip_address so you can easily clear all sessions for a given user.

Conclusion

Hope you have learned about some of the exclusive features about the latest version of Laravel: Laravel  5.2. Hang around as I’m planning to write about some of the latest web development technologies.

Learn More From Our Techies

Table of Contents

    Contact Us

    Contact

    What's on your mind? Tell us what you're looking for and we'll connect you to the right people.

    Let's discuss your project.

    Phone