8

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

2
  • 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 Commented Jun 4, 2015 at 11:21
  • did you get the answer to this? Commented May 26, 2022 at 6:30

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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 :)

2 Comments

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...
@AngelinCalu That might be true, but the question was not about best practises. Sometimes a quick hack is all you need ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.