Laravel User
Laravel User

Reputation: 1129

Laravel 5.2 : How to get a variable in a subView of a parentView from another subView?

Below is my views and controllers i want $name variable to be accessible in navbar view which is included in master view. does anybody know a solution ?

userController.php

public function index($var){
    $u_array = $var;
    $name = $u_array->name;
    return view('index',compact(name));
}

master.blade.php

@include('navbar')
<section class="main-container">
    @yield('content')
</section>

index.blade.php

@extends('master')
@section('content')
    <h2>{{$name}}</h2>
@endsection

navbar.blade.php

<h1>{{$name}}</h1>

Upvotes: 3

Views: 1004

Answers (3)

Veer Singh
Veer Singh

Reputation: 36

you can use @section in index view and @yield in navbar view as

index.blade.php

@extends('master')
@section('content')
    <h2>{{$name}}</h2>
@endsection
@section('nav')
    <h1>{{$name}}</h1>
@endsection

navbar.blade.php

@yield(nav)

Upvotes: 2

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

Pass the variable to master.blade then navbar.blade:

@extends('master', ['name' => $name]) //compact('name')

Then:

@include('navbar', ['name' => $name]) //compact('name')

Upvotes: 3

ExohJosh
ExohJosh

Reputation: 1892

You should use a view composer for this.

View Composer

view()->composer('master', function ($view) {
  $u_array = $var;
  $name = $u_array->name;
  $view->with(compact(name));
});

With some more explanation on your specific issue I may be able to assist you in better alternatives.

Upvotes: 0

Related Questions