简体   繁体   中英

How to get variable in Laravel blade @foreach loop from outer view

I have blade view with @foreach loop. In this blade view I also pass on $user variable in UserController. Inside @foreach I have code {{ $user->getAvatar() }} .

@extends('layouts.app')

@section('content')

@foreach($threads as $thread)
    <div class="media alert {{ $class }}">
        <img src="{{ $user->getAvatar() }}">
        <div class="media-body">
            <p>
            {{ $thread->latestMessage->body }}
            </p>
        </div>    
    </div>
@endforeach

@endsection

This is index() function in my controller

public function index()
    {
        $user = Auth::user();
        $threads = Thread::getAllLatest()->get();
        return view('messenger.index', compact('threads', 'user'));
    }

I have error Undefined variable: user . foreach loop don't see variable from other part of view.

ErrorException (E_ERROR)
Undefined variable: user (View:messenger\partials\thread.blade.php) (View: messenger\partials\thread.blade.php)
Previous exceptions
Undefined variable: user (View: messenger\partials\thread.blade.php) (0)
Undefined variable: user (0)

In your case, please use this code on return

return View::make('messenger.index')

->with(compact('threads'))

->with(compact('user'));

You can use with as many time as you want . This will resolve your issue hopefully.

You need to check if variable has value or not, if laravel failed to get value of $user->getAvatar() it will definitely return error so just try following

@isset($user->getAvatar())

@endisset

Try with this:

@foreach($threads as $thread)
    <div class="media alert {{ $class }}">
        <img src="{{ isset($user) ? $user->getAvatar : '' }}">
        <div class="media-body">
            <p>
            {{ $thread->latestMessage->body }}
            </p>
        </div>    
    </div>
@endforeach

Try defining it above foreach loop

@extends('layouts.app')

@section('content')
<?php 
   $user_avatar = $user->getAvatar();
?>
@foreach($threads as $thread)
<div class="media alert {{ $class }}">
    <img src="{{ $user_avatar }}">
    <div class="media-body">
        <p>
        {{ $thread->latestMessage->body }}
        </p>
    </div>    
</div>
@endforeach

@endsection

Hope it Helps !

Why you don't use auth() helper function instead

<img src="{{ auth()->user()->getAvatar() }}">

This way you don't need to pass it trough the controller.

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