0

Can I do something similar to this in Laravel Blade:

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

Maetschl
  • 1,330
  • 14
  • 23
InFo55
  • 13
  • 8
  • Can you give an example of what you're after and also the `CustomClass` that you want to "cast" the items to. – Rwd Jan 09 '20 at 15:02
  • So I make a call to a third party API and I get the object which I map it into a custom class. Now I have a collection of objects of this custom class which I want to pass to my view from the controller. I want to use the get methods of my class for type safety in blade and to do so I think casting is needed. – InFo55 Jan 09 '20 at 15:06
  • Is something like this what you're after: https://laravel.com/docs/master/collections#method-mapinto? – Rwd Jan 09 '20 at 15:08
  • @Rwd I don't think this is what he needs, since it will not provide him a safety type in Blade. What he looks after is more like generics, something like Collection, where all objects inside this collections can only be used as a CustomClass object, with an autocompletion on each available methods and properties. Is that it ? – Anthony Aslangul Jan 09 '20 at 15:17

3 Answers3

1

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
}
Anthony Aslangul
  • 3,589
  • 2
  • 20
  • 30
0

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();
}
HubertNNN
  • 1,727
  • 1
  • 14
  • 29
0

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

Good Muyis
  • 127
  • 9