Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Undefined variable on first try

Tags:

php

laravel

one of the weirdest error happened to me this morning

when I open the show blade of my model on 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 reopen it 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 is :

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

what is the problem

like image 371
mohamadreza Avatar asked Oct 17 '22 19:10

mohamadreza


1 Answers

Update your piece of code with below one:

<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 issue while if ($place->media) fails.

like image 100
AddWeb Solution Pvt Ltd Avatar answered Oct 21 '22 02:10

AddWeb Solution Pvt Ltd