Laravel Undefined variable on first try

One of the strangest mistakes happened to me this morning

when I first open the blade of my model on the first try, I get this

Undefined variable: engs (View: C: \ wamp64 \ www \ Form \ resources \ views \ dashboard \ placeShow.blade.php)

But when I refresh the page or open it again, everything works

my controller:

public function showPlace($id) { $place = Place::find($id); if (!$place->seen->contains(Auth::user()->id)) { $place = $place->seen()->save(Auth::user()); } if ($place->media) { $media = $place->media; $engs = $media->where('category', 'engs'); $heritages = $media->where('category', 'heritages'); $estates = $media->where('category', 'estates'); $others = $media->where('category', 'others'); return view('dashboard.placeShow')->with(['place' => $place, 'engs' => $engs, 'heritages' => $heritages, 'estates' => $estates, 'others' => $others]); }else{ return view('dashboard.placeShow')->with(['place' => $place]); } 

and my blade:

 <ul> @foreach($engs as $eng) <li><a target="_blank" href="/{{$eng->href}}">{{$eng->old_name}}</a></li> @endforeach </ul> 

what is the problem

+5
source share
1 answer

Update your code snippet below:

 <ul> @if(isset($engs)) @foreach($engs as $eng) <li><a target="_blank" href="/{{$eng->href}}">{{$eng->old_name}}</a></li> @endforeach @else <li>Records not found..!</li> @endif </ul> 

I think this problem so far if ($place->media) fails.

+3
source

Source: https://habr.com/ru/post/1262017/


All Articles