Home » Php » php – Laravel – How to pass variable to layout partial view

php – Laravel – How to pass variable to layout partial view

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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.

Answer:

This approach is very simple:

In parent view :

@include('partial.sub_view1', ['This is value1' => $var1])

In sub view :

{{ $var1 }}

Answer:

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 }}

Answer:

@include(‘your view address’, array(‘variable in your view for example: id=$something ‘ => ‘value for this variable’))