30

I was trying to do include with Laravel blade, but the problem is it can't pass the variable. Here's my example code:

file_include.blade.php

<?php $myvar = "some text"; 

main.blade.php

@include('file_include') {{$myvar}} 

When I run the file, it return the error "Undefined variable: myvar". So, how can I pass the variable from the include file to the main file?

Thank you.

1
  • @include is used to include sub views , it shouldn't be used to load variables this way. Remember these are blade templates and not regular php files. Commented Dec 15, 2015 at 13:07

6 Answers 6

54

Why would you pass it from the include to the calling template? If you need it in the calling template, create it there, then pass it into the included template like this:

@include('view.name', array('some'=>'data')) 

Above code snippet from http://laravel.com/docs/templates

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

2 Comments

Unfortunately this is not the solution If you need to get variable from different page! Check my answer please, You will understand what I mean
Good point. My answer didn't really address the actual question. Instead, I offered a solution that would not involve passing a variable. However, if one needs to pass a variable in, your solution is excellent for that!
9

Unfortunately Laravel Blade engine doesn't support what you expected!.But a little traditional way you can achieve this!

SOLUTION 1 - without Laravel Blade Engine

Step a:

from

file_include.blade.php 

to

file_include.php 

Step b:

main.blade.php

<?php include('app/views/file_include.php') ?> {{$myvar}} 

SOLUTION 2 with Laravel Blade Engine

routes.php

$data = array( 'data1' => "one", 'data2' => "two", ); View::share('data', $data); 

Access $data array from Any View like this

{{ $data['data1'] }} 

Output

one 

Comments

2

Blade is a Template Engine for Laravel. So try passing the value from the controller or you may define it in the routes.php for testing purposes.

@include is used to include sub-views.

Comments

1

I think you must understand the variable scope in Laravel Blade template. Including a template using @include will inherit all variables from its parent view(the view where it was defined). But I guess you can't use your defined variables in your child view at the parent scope. If you want your variable be available to the parent try use View::share($variableName, $variableValue) it will be available to all views as expected.

Comments

0

In this scenarion $myvar would be available only on the local scope of the include call.

Why don't you send the variable directly from the controller?

Comments

0

I suggest you do a classic PHP require if you really want to change your variable (then it's automatically by reference)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.