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?
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.
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With