In the laravel framework, I have several nested views as follows
<mainview>
loop @include <sub-view>
loop @include <sub-sub-view>
I would like to keep a counter of just how many sub-sub-views there are. It becomes, in effect, a row counter. I am not sure where to declare/init this variable ($sub-sub-view-counter), and where to increment it along the way. No matter where I put it, it can’t be seen and incremented by every view.
This is maybe a bit of a hack, but unless nothing better comes up…
You will need either a helper function or an object (easiest way is to put that to the models). For demonstration I chose the object variant, as I believe it’s a bit easier to handle and most of all easier to extend to your needs. Also this implicitly supports multiple counters, as the value is saved per-object (You’d have to jump through a few hoops to get this functionality with a function).
So for this specific implementation you will have to create it somewhere. You can either put a line like this in your parent view somewhere before including your sub-views, or inject it from PHP with the
with()method.You include the sub-view like usual (remember to use
include, notrender, to keep the$countervariable) I used aforloop for testing, but you can of course use any variant you want.And finally you can just call this in the sub-view
You can easily extend this model with a factory to get counter values from anywhere in your application, but for your use case this basic variant should be enough.