Passing Variables to Laravel View Blades from Controllers

Hello,

This is my first blog on Laravel. I have been working with Laravel since last few weeks. It’s a nice and flexible framework. In this blog I am going to explain how you can pass variables to Laravel view blade from controllers.

This will help you when you want to pass some variables that may have boolean values using which you want to show hide some part of UI or you want to pass arrays to view and iterate through it and create dynamic html. So first we are going to create views inside controller as follow.

$this->layout->content = View::make(‘Views.View1’);

This will call Views.View1.blade.php file and render it’s layout.

Now lets assume we want to pass variables to it as we have following code in view.

 @if ($showDiv == true)
<div> This div will only be visible if $showDiv variable is set to true </div&gt
@endif

Also lets assume we want to iterate through and array and create dynamic list.

<ul class=”dropdown-menu”>
      @foreach ($names as $name)
               <li>{{$name}}</li>
      @endforeach
</ul>

Now lets see how to pass this.

In your controller create variables as folllow

$showDiv = true;
$names = array(“John”, “Jack”, “Smith”, “James”);

Now we will share this variable with view using share function.

View::share(‘showDiv’, $showDiv);
View::share(‘names’, $names);

That’s it, now these variables are available in view and views will be rendered according to logic. So key thing is to use share function of view to share variables with view. If you don’t share like this you may get an error that variable in blade undefined.

This entry was posted in DataView, Laravel, MVC, PHP, PHP Framework on by .

About Hiren Dave

Hiren Dave is a software engineer, blogger and consultant with over 9 years of professional experience. He writes code in number of languages. Hiren has a passion for developing web apps, mobile apps and writing books and blog articles about programming. He has a solid experience of startups as he manages products for few startups. He is also passionate about researching and learning new technologies and trends. He has also authored a book Instant Sencha Touch, published by Packt and creator of Video Course "Beginning Laravel" for Packt

Leave a Reply

Your email address will not be published. Required fields are marked *