Ad

Undefined Variable

- 1 answer

I still get this error for some I guess stupid reason. I was following Laracast fundamentals tutorials then I decided to create my own app and it's the same. Probably I've messed something up and can't see it.

Here's the error:

Undefined variable: movies (View: C:\Users\username\PhpstormProjects\movie_app\resources\views\movies\show.blade.php)

This is my controller:

public function show($id)
{
    $movie = Movie::findOrFail($id);
    return view('movies.show', compact('movie'));
}

View:

@extends('layouts.app')
@section('content')
    @foreach($movies as $movie)
        <h4>{{$movie->name}}</h4>
    @endforeach
@endsection
Ad

Answer

Because you are not returning collection you can't use foreach.

To echo the movie call the object name directly:

@extends('layouts.app')
@section('content')
   <h4>{{$movie->name}}</h4>
@endsection

And yet you call wrong variable name at your view. You return movie not movies.

Ad
source: stackoverflow.com
Ad