Ad

Can I Cast A Custom Class To A Variable In Blade Laravel

Can I do something similar to this in Laravel Blade:

@foreach($collection as (CustomClass) $object)

Ad

Answer

This is not possible. Since Blade is a PHP templating language, you can only do what PHP allows... and it doesn't allow you to cast a type on local variable.

You can only type hint function parameters and - in the newly released PHP 7.4 - class properties. You can also give your function a return type.

PHP 7+:

public function foo(string $bar): int
{
    return strlen($bar);
}

PHP 7.4+ :

   protected int $count;

Of course, my examples are made with scalar types (string, int, float, boolean) but you could totally put a custom class here.

public function logout(App\User $user)
{
    //stuff
}
Ad
source: stackoverflow.com
Ad