Can I do something similar to this in Laravel Blade:
@foreach($collection as (CustomClass) $object)
Can I do something similar to this in Laravel Blade:
@foreach($collection as (CustomClass) $object)
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
}
You could use Collection::whereInstanceOf()
to filter out anything that is not of your desired class.
https://laravel.com/docs/5.8/collections#method-whereinstanceof
@foreach($collection->whereInstanceOf(CustomClass) as $object)
If you want to simply error out if something that is not your class then you could compare sizes of the collections. But I suggest doing it in the controller:
if ($collection->whereInstanceOf(CustomClass)->count() !== $collection->count()) {
throw Exception();
}
You provide little information in your question but since you are using @foreach, you can typecast as follow which should work:
@foreach($collection as $object)
@php($object = (object)$object)
......
@endforeach
This should allow you to use $object->item