pieter771
pieter771

Reputation: 53

Undefined variable Laravel Foreach

I want to foreach some data but it says it doesn't know the variable:

The error I get:

    ErrorException in dbda158712a631f22ffd888cd244c74e60f3a433.php line 51:
Undefined variable: albums (View:        /var/www/clients/client2/web2/web/resources/views/album.blade.php)

Here is my code:
Album.blade.php

@foreach($albums as $others)
    <option value="{{$others->id}}">{{$others->name}}</option>
@endforeach

My album controller function

  public function getAlbum($id)
  {
    $album = Album::with('Photos')->find($id);
    return View::make('album')
    ->with('album',$album);
  }

  public function getList()
  {
    $albums = Album::with('Photos')->get();
    return View::make('index')
    ->with('albums',$albums);
  }

Upvotes: 0

Views: 2831

Answers (2)

Nicholas
Nicholas

Reputation: 61

Try This Code.

 public function getAlbum($id)
 {
      $albums=albums::with('Photos')->get();

       $album=albums::with('Photos')->find($id);

       return view('album',compact('albums','album'));

 }

Upvotes: 0

Vikash
Vikash

Reputation: 3551

You are passing album variable with view Album.blade.php, which is single object, not array of object so you can't iterate in a loop.

I think you are doing a mistake.

You want to do foreach in index.blade.php, because here you are passing the albums variable.

or

you need to return view album.blade.php in your getList function.

Upvotes: 3

Related Questions