Foreach循环在我看来有未定义的变量

时间:2018-12-24 09:10:34

标签: laravel laravel-5

该错误显示在视图上

  

我的$ audio变量未定义。

我想使用foreach循环显示数据库中的所有内容。

我在laravel文档https://laravel.com/docs/5.7/pagination#basic-usage上基于分页进行了尝试

我的控制器在下面:

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]);
}

欢迎视图如下:

<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>

我的路线web.php在下面:

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

我希望将所有音频讲座从数据库显示到视图中。

2 个答案:

答案 0 :(得分:6)

尝试这个

@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
  

您从控制器 audio_lectures 数组传递,但是您   在您看来音频

答案 1 :(得分:1)

在您的查看文件循环中,尝试此

@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