New Laravel v8.70 Released – Check Features and Changes

Laravel

Laravel v8.70 is now released with many new features like JS class, can() method, –requests flag for controller and model to create a FormRequest class automatically.

Let’s have a detailed look into each feature below:

The Js Facade

Sometimes we may pass an array to a view and assign it to a JavaScript variable. For Example:

<script>
    var variable_a = <?php echo json_encode($array_variable); ?>;
</script>

However, instead of calling PHP’s json_encode, we can use Js::from method directive. The from method will ensure that the resulting JSON is properly escaped for inclusion within HTML quotes. The result of from method will be a string  JSON.parse JavaScript statement that will convert the given object or array

<script>
    var variable_a = {{ Illuminate\Support\Js::from($array_variable) }};
</script>

We can also add it in  aliases key of config/app.php  file so that we can access it using Js facade class.

<script>
    var variable_a = {{ Js::from($array_variable) }};
</script>

The can() Method

Laravel 8.70 introduced a can() method that can validate a request even before passing it to a route or controller.

The Laravel official doc shows below example:

use App\Models\Post;

Route::put('/post/{post}', function (Post $post) {
    // The current user may update the post...
})->middleware('can:update,post');

In the above example, we are passing 2 arguments to can middleware. The first argument is an action name which we are authorizing and the second argument is a route variable – post. If a user is not allowed to perform an update action, then middleware will return a 403 status.

–request flag

This version added a new --requests flag, which creates a FormRequest class and uses it immediately in the generated controller. An example command is:

php artisan make:controller UserController \
  --resource \
  --model=User \
  --requests

enum Validation Rule

enum validation rules will verify whether the field has only allowed value from the enum set. For this, laravel v8.70 added a Enum class which takes the name of enum as an argument.

use App\Enums\DeviceList;
use Illuminate\Validation\Rules\Enum;

$request->validate([
    'device' => [new Enum(DeviceList::class)],
]);

Please note that enums are supported only in >PHP 8.1.

You can see a detailed comparison of v8.60 and v8.70 here.

Leave a Reply

Your email address will not be published. Required fields are marked *