7

I'm including multiple templates in a loop by using

@include('template.included')

Before including this template I define

$page = 0;

and inside the template, multiple times it calls

$page++;

Inside the included template, the value correctly increments, however outside the template it seems like the $page variable stays the same - it's looking like @include creates it's own copy of each var you use.

I need this $page variable to update from inside those templates, and have it's value returned back to my main template - am I missing something simple?

Appreciate any suggestions!

EDIT:

My issue, for example:

$page = 0;
@include('template.included') //This calls $page++ 5 times
echo $page; //returns 0

I need $page to return 4, not 0

Josh Undefined
  • 1,496
  • 5
  • 16
  • 27
  • I have no issue accessing the variable within the template, however I want the changes I make within the included file to update the variable outside the template. I'll add an edit of another example to hopefully make it clearer – Josh Undefined Jun 04 '15 at 11:21
  • did you get the answer to this? – AnkitS May 26 '22 at 06:30

2 Answers2

1

Your assumption is correct, Laravel's view system does creates a new scope for each view it loads. The Illuminate\View\Factory::make() method which is used when including views, does this:

new View($this, $this->getEngineFromPath($path), $view, $path, $data)

It's creating a new view and passing the data to it, which effectively means it's sending a copy of the information. Since arguments there are not passed by reference (which was deprecated and in newer PHP versions is already removed), what you want can't be done.

That being said, your approach seems flawed. It looks to me like you're building the pagination in the view, which is something you should not be doing there. Laravel already offers a very easy way to create Pagination, you should perhaps look into that.

Bogdan
  • 43,166
  • 12
  • 128
  • 129
0

You can do this using the global variable in PHP. So in your main blade page you define your variable like this:

$page = 0;

Then inside the included blade page you do this:

global $page;
$page++;

This works for me just fine :)

Pieter
  • 1
  • 2
  • global variables and Laravel don't really play along very well :) It's just as you would install an old cassette player on a brand new car. It would work, but... – Angelin Calu Mar 10 '22 at 08:28
  • @AngelinCalu That might be true, but the question was not about best practises. Sometimes a quick hack is all you need ;) – Pieter Mar 12 '22 at 09:02