Josh Undefined
Josh Undefined

Reputation: 1536

Laravel - Modify and return variable from @include

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

Upvotes: 8

Views: 1829

Answers (2)

Pieter
Pieter

Reputation: 1

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

Upvotes: 0

Bogdan
Bogdan

Reputation: 44526

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.

Upvotes: 1

Related Questions