Skip to content
Advertisement

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)

Advertisement

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(AppUser $user)
{
    //stuff
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement