Codekutu

What is new in Laravel 7 with examples

Laravel 7 is now released which includes improvements from Laravel 6.x and many new features. Some of the new features are

  • Laravel Airlock
  • Better routing speed
  • Custom Eloquent casts
  • Blade component tags
  • Fluent string operations
  • A new HTTP client
  • CORS support

Laravel Airlock

With Laravel Airlock package you can handle authentication for your single page applications, mobile applications and for simple token based APIs. The users of your application will be able to generate more than one API tokens for their account. Different permissions will be given to those tokens for authorization.

Installing Airlock package

To use Laravel Airlock package on your Laravel application you need to install it first, publish the configuration and migration file and then run the migrations.

Laravel Airlock package can be installed with Composer as:

composer require laravel/airlock

To publish the Airlock configuration and migration files with vendor:publish artisan command.

php artisan vendor:publish --provider=”Laravel\Airlock\AirlockServiceProvider”

Database migrations can be run with migrate artisan command as:

php artisan migrate

Also for authenticating single page application, you need to add the Airlock middleware to your application api middleware group inside app/Http/Kernel.php file as:

use Laravel\Airlock\Http\Middleware\EnsureFrontendRequestsAreStateful;

'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

Working with API Tokens

To create API tokens for authenticating API requests for your users, first you need to add HasApiTokens trait on your User model as:

use Laravel\Airlock\HasApiTokens;

class User extends Authenticatable {
    use HasApiTokens, Notifiable;
}

To create a token for a user you can use the createToken method which will return a Laravel\Airlock\NewAccessToken instance as:

$userToken = $user->createToken(‘my-token-name’);

The API token will be hashed with SHA-256 value and stored on the database and can be accessed as the plain-text with plainTextToken method as:

$userPlainToken = $userToken->plainTextToken;

You can use tokens Eloquent relationship from HasApiTokens to access all user’s tokens as:

foreach ($user->tokens as $userToken) {
   /* Do something with token */
}

You can assign permissions to tokens by passing an array of string permissions on the createToken method second argument as:

return  $user->createToken(‘my-token-name’, [‘post:delete’])->plainTextToken;

And you can verify permission from the request with Airlock by using tokenCan method as:

if ($user->tokenCan(‘post:delete’)) {
    /* Deleting the post */
}

Custom Eloquent Casts

With Laravel you can define the type of value to be returned from the model by using custom cast types. This is very helpful when you want a specific data type to be returned from the database.

To create a custom cast type you need to define a class which implements the CastsAttributes interface. In your class you should implement the set method for changing the cast value to a raw value which can be stored in the database, and the get method for changing the raw value from the database to cast value.

For example our User model has a clothes attribute which will store the type of clothes the user wears in a json format. We can create a custom Json type which will encode the value to json and store them to the database also will decode them when we want to view the value.

The class will be like this:

<?php

namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Json implements CastAttributes {
	public function get($model, $key, $value, $attribute) {
		return json_decode($value, true);
	}

	public function set($model, $key, $value, $attribute) {
		return json_encode($value);
	}
}

Then you will need to attach the created class with your User model and specify which attribute should be casted with $casts property. $casts property present in Laravel models which provides a way to convert attributes to common data types.

The User model class will look like this:

<?php

namespace App;

use App\Casts\Json;
use Illuminate\Database\Eloquent\Model;

class User extends Model {
	protected $casts = [
		'clothes' => Json::class	
	];
}

Fluent String Operations

There is a String class from Illuminate\Support\Str in Laravel which provides different methods to work with strings. In Laravel 7 there is a better object-oriented way to create a fluent string from Illuminate\Support\Stringable class by using the Str::of method.

You can also chain different methods to manipulate your string, like:

return (string) Str::of(‘ I like learning from Codekutu ‘)
			->trim()
			->replace(‘I’, ‘We’);

Some of the fluent string methods for manipulating the strings are:

  • after – Returns everything after the given value.
  • append – Returns a string with an appended given value.
  • ascii – Returns a translated string into an ASCII value.
  • camel – Returns a string converted into a camelCase format.
  • explode – Returns a collection of the splitted string in each section.
  • slug – Returns a generated URL friendly value from the string.
  • snake – Returns a converted string into snake_case format.
  • words – Returns a limited number of words from a string.

You can read more on Laravel 7 Documentation and from Laravel version 6, Laravel will follow semver and after every six months they will be releasing a new major version.

Add comment

Keep in touch

It is easy, click the button and follow us. We like sharing ideas and making friends.