php - 未定义的变量: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"></i></a>
<a onclick="event.preventDefault();deletemhsForm({{$mhs->id}});" href="#" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete"></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”
有谁知道这是什么原因?
解决方案
您正在传递一个名为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"></i></a>
<a onclick="event.preventDefault();deletemhsForm({{$mhs->id}});" href="#" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete"></i></a>
</td>
</tr>
@endforeach
或在您的控制器中:
public function index(Request $request)
{
$mhs = Dashboard::orderBy('id', 'desc')->paginate(5);
return view('frame')->with('mahasiswa', $mhs);
}
推荐阅读
- java - 为什么打印“”+变量单独输出每个变量而没有空格?
- rest - 当某些属性可以更改而某些属性不能基于资源的状态时,如何创建一个好的 PATCH 端点?
- java - 如何使用包裹传递地图列表?
- vue.js - 错误:通过导航守卫从“/pages/login”转到“/dashboard”时重定向
- python - 如何将给定订单列表转换为给定订单的json
- json - Webhook 不返回 JSON
- docker - Kafka微服务升级最好最简单的方法是什么
- java - 有什么方法可以有效地同步两个数据库?
- cpython - python c api,如何将函数添加到c层中定义的类
- python - 字典的类型错误:+ 的不支持的操作数类型:“int”和“str”