简体   繁体   中英

How to access a variable value in another view in blade template?

My Views Code in blade template is like this:

Views/Mainview.blade.php

@extends('layouts.app')
@section('content')
    @php 
        $baalgh = array();
    @endphp
    @include('tabs.familyview')
    <?php print_r($baalgh); //prints empty array ?>
    @include('tabs.childview') //need $baalgh value inside this view
@endsection

Views/tabs/familyview.blade.php

@foreach($membersdata as $key=>$onemember)
    @php 
        $age = calculateage($onemember->memberdob);
        $onemember->age = $age;
        ((18 <=> $age) === 1)?:$baalgh[] = $onemember;
    @endphp
@endforeach
<?php print_r($baalgh); //here it displays data ?>

my question is how to access values of $baalgh in mainview and childview ?

Your code seems a bit unorganized, you should try to keep the calculations inside your controller, and use the views as the presentation of your calculated data. I suppose you can do something like this:

In your controller:

$baalgh = $membersdata->filter(function($total, $member){
    $member->age = calculateage($member->memberdob);
    return $member->age <=> 18;
});

return view("Mainview.blade.php", ["baalgh" => $baalgh, "membersdata" => $membersdata]);

Then in your Views/Mainview.blade.php :

@extends('layouts.app')
@section('content')
    @include('tabs.familyview')
    @include('tabs.childview')
@endsection

And on your Views/tabs/familyview.blade.php :

<?php print_r($baalgh); //here it displays data ?>

It is much simpler this way.

Just follow simple steps for include array into child view:

Views/Mainview.blade.php

@extends('layouts.app')
    @section('content')
    @php 
        $baalgh = array();
    @endphp
    @include('tabs.familyview', ['baalgh' => $baalgh])
    {{ var_dump($baalgh) }} //prints empty array

@endsection

Views/tabs/familyview.blade.php

@foreach($membersdata as $key=>$onemember)
    @php 
        $age = calculateage($onemember->memberdob);
        $onemember->age = $age;
        ((18 <=> $age) === 1)?:$baalgh[] = $onemember;
    @endphp
@endforeach
<?php print_r($baalgh);

 @include('tabs.childview', ['baalgh' => $baalgh])

Views/tabs/childview.blade.php

@foreach ($baalgh as $baal)
    {{$baal}} // $baalgh array is updated.
@endforeach

I hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM