Reputation: 157
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)
Upvotes: 3
Views: 2915
Reputation: 1399
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.
Upvotes: 0
Reputation: 115
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.
Upvotes: 2
Reputation: 2453
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 !
Upvotes: 0
Reputation: 1050
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
Upvotes: 0
Reputation: 3541
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
Upvotes: 0