Nebulanoob
Nebulanoob

Reputation: 55

Foreach loop has undefined variable in my view

The error is on the view which says that

my $audio variable is not defined.

I want to show everything from the database using a foreach loop.

I tried base on paginate on the laravel documentation https://laravel.com/docs/5.7/pagination#basic-usage

My controller is below:

use Illuminate\Http\Request;
use App\Audio_lectures;
use Illuminate\Support\Facades\DB;

public function index(){
        $audio = DB::table('audio_lectures')->latest()->paginate();
        return view('welcome', ['audio_lectures' => $audio]);
}

The welcome view is below:

<div class="container">
  <div class="row">
<table class="table table-dark">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Subject</th>
      <th scope="col">Date Added</th>
      <th scope="col">Download</th>
    </tr>
  </thead>
  <tbody>
    @foreach ($audio as $audio_lectures)
    <tr>
      <th scope="row">{{$audio_lectures->id}}</th>
      <td>{{$audio_lectures->subject}}</td>
      <td>{{$audio_lectures->created_at}}</td>
      <td><a href="{{$audio_lectures->filelink}}" class="btn btn-outline-light btn-sm">Download</a></td>
    </tr>
    @endforeach
  </tbody>
</table>
</div>
</div>

My route web.php is below:

Route::get('/','Audio_lecturesController@index');  

I expect to show all the audio lectures from my database to my view.

Upvotes: 0

Views: 1028

Answers (2)

Jignesh Joisar
Jignesh Joisar

Reputation: 15115

try this one

@foreach ($audio_lectures as $audio)
   <tr>
      <td scope="row">{{$audio->id}}</td>
      <td>{{$audio->subject}}</td>
      <td>{{$audio->created_at}}</td>
      <td>
         <a href="{{$audio->filelink}}" class="btn btn-outline-light btn-sm">Download</a>
      </td>
   </tr>
@endforeach

you are passing from controller audio_lectures array but you getting as in your view audio

Upvotes: 6

MD. Jubair Mizan
MD. Jubair Mizan

Reputation: 1560

On your view file looping try this

@foreach ($audio_lectures as $value)
   <tr>
      <td scope="row">{{$value->id}}</td>
      <td>{{$value->subject}}</td>
      <td>{{$value->created_at}}</td>
      <td><a href="{{$value->filelink}}" class="btn btn-outline-light btn-sm">Download</a></td>
   </tr>
@endforeach

Upvotes: 1

Related Questions