-3

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
r0uder
  • 25
  • 5
  • 1
    Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Albert221 Jan 10 '16 at 13:03
  • your vairable is `$movie` not `$movies` – eMad Jan 10 '16 at 13:04

1 Answers1

1

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.

ssuhat
  • 7,387
  • 18
  • 61
  • 116
  • Got that: "Trying to get property of non-object" If I change the controller I still get the same error :(. – r0uder Jan 10 '16 at 13:01
  • my bad. wait will fix my answer – ssuhat Jan 10 '16 at 13:02
  • I've update my answer. try that one – ssuhat Jan 10 '16 at 13:03
  • It worked. So, If I have the only one movie in my database it won't work because it isn't a collection yet, correct? – r0uder Jan 10 '16 at 13:05
  • nope. It's not depend on the database. You can have 500 movies but the problem is on what are your query return the result. You return it in single item not a collection. read more here: https://laravel.com/docs/5.2/eloquent#retrieving-multiple-models – ssuhat Jan 10 '16 at 13:07
  • Thank you, now I get it. – r0uder Jan 10 '16 at 13:11