Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - How to pass variable to layout partial view

I have a partial view in master layout which is the navigation bar. I have a variable $userApps. This variable checks if the user has enabled apps (true), if enabled then I would like to display the link to the app in the navigation bar.

homepage extends master.layout which includes partials.navbar

My code in the navbar.blade.php is this:

@if ($userApps)
    // display link
@endif

However I get an undefined variable error. If I use this in a normal view with a controller it works fine after I declare the variable and route the controller to the view. I dont think I can put a controller to a layout since I cant route a controller to a partial view, so how do I elegantly do this?

like image 742
pleasega Avatar asked Jul 17 '16 07:07

pleasega


2 Answers

What version of Laravel you use? Should be something like this for your case:

@include('partials.navbar', ['userApps' => $userApps])

Just for a test purpose, I did it locally, and it works:

routes.php

Route::get('/', function () {
    // passing variable to view
    return view('welcome')->with(
        ['fooVar' => 'bar']
    );
});

resources/views/welcome.blade.php

// extanding layout
@extends('layouts.default')

resources/views/layouts/default.blade.php

// including partial and passing variable
@include('partials.navbar', ['fooVar' => $fooVar])

resources/views/partials/navbar.blade.php

// working with variable
@if ($fooVar == 'bar')
  <h1>Navbar</h1>
@endif

So the problem must be in something else. Check your paths and variable names.

like image 149
Yuri Tkachenko Avatar answered Nov 04 '22 22:11

Yuri Tkachenko


The other answers did not work for me, or seem to only work for older versions. For newer versions such as Laravel 7.x, the syntax is as follows.

In the parent view:

@include('partial.sub_view', ['var1' => 'this is the value'])

In the sub view:

{{ $var1 }}
like image 7
gpsugy Avatar answered Nov 04 '22 20:11

gpsugy