首页 > 解决方案 > 未定义的变量:laravel foreach 中的错误

问题描述

我正在尝试将数据库中的数据检索到我的 Laravel CRUD 中,但它在我的视图中显示未定义的变量。

这是视图 frame.blade.php

@foreach($mahasiswa as $mhs)
   <tr>
       <td>{{$mhs->id}}</td>
       <td>{{$mhs->nim}}</td>
       <td>{{$mhs->nama}}</td>
       <td>{{$mhs->alamat}}</td>
       <td>{{$mhs->fakultas}}</td>
       <td><a onclick="event.preventDefault();editmhsForm({{$mhs->id}});" href="#" class="edit open-modal" data-toggle="modal" value="{{$mhs->id}}"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a>
           <a onclick="event.preventDefault();deletemhsForm({{$mhs->id}});" href="#" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a>
       </td>
       </tr>
@endforeach

这是控制器

use App\Dashboard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class DashboardController extends Controller
{

public function index(Request $request)
{
    $mhs = Dashboard::orderBy('id', 'desc')->paginate(5);

    return view('frame')->with('frame', $mhs);
}

这是路线

Route::group(['prefix' => 'mahasiswa'], function () {
    Route::get('/dashboard/{id}', [
        'uses' => 'DashboardController@show',
        'as'   => 'mahasiswa.show',
    ]);

    Route::post('/dashboard/', [
        'uses' => 'DashboardController@store',
        'as'   => 'mahasiswa.store',
    ]);

    Route::put('/dashboard/{id}', [
        'uses' => 'DashboardController@update',
        'as'   => 'mahasiswa.update',
    ]);

    Route::delete('/dashboard/{id}', [
        'uses' => 'DashboardController@destroy',
        'as'   => 'mahasiswa.destroy',
    ]);
});

在我看来,我不断收到“未定义的变量:mahasiswa”

有谁知道这是什么原因?

标签: phplaravellaravel-5

解决方案


您正在传递一个名为frame并尝试迭代的数据$mahasiswa,所以要么将您的刀片更改为:

@foreach($frame as $mhs)
   <tr>
       <td>{{$mhs->id}}</td>
       <td>{{$mhs->nim}}</td>
       <td>{{$mhs->nama}}</td>
       <td>{{$mhs->alamat}}</td>
       <td>{{$mhs->fakultas}}</td>
       <td><a onclick="event.preventDefault();editmhsForm({{$mhs->id}});" href="#" class="edit open-modal" data-toggle="modal" value="{{$mhs->id}}"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a>
           <a onclick="event.preventDefault();deletemhsForm({{$mhs->id}});" href="#" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a>
       </td>
       </tr>
@endforeach

或在您的控制器中:

public function index(Request $request)
{
    $mhs = Dashboard::orderBy('id', 'desc')->paginate(5);

    return view('frame')->with('mahasiswa', $mhs);
}

推荐阅读