[英]local.ERROR: exception 'ErrorException' with message 'Undefined variable
[英]Exception message: Undefined variable:
我正在嘗試使用 laravel 從 mysql 數據庫中檢索數據。 它顯示錯誤undefined variable
視圖.blade.php
<table>
<tr>
<th>Title</th>
<th>Body</th>
<th>Category</th>
</tr>
@foreach($post as $row)
<tr>
<td>{{$row['title']}}</td>
<td>{{$row['body']}}</td>
<td>{{$row['category_id']}}</td>
</tr>
@endforeach
</table>
后控制器代碼
public function index()
{
$post = posts::all()->toArray();
return view('view',compact('post'));
}
我希望它顯示我的數據庫表的結果,但它顯示錯誤Undefined variable
首先通過cmd進入項目文件夾,然后,
php artisan make:model Posts.
您將在App
文件夾中創建名為Posts.php
文件
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Posts extends Model
{
protected $table = 'posts';
protected $fillable = [
'title', 'body','category_id'
];
}
不要忘記在控制器頂部包含模型的命名空間,例如:
use App\Posts;
然后在你的索引方法中,
public function index()
{
$post = Posts::all();
return view('your_views_correct_path',compact('post'));
}
不需要通過將其轉換為數組來傳遞您的帖子集合以進行查看。 只需按上圖所示傳遞帖子即可。 然后您可以通過在foreach
循環中循環 post 集合來輕松訪問 post 屬性。
@if(!empty($post))
@foreach($post as $p)
{{ $p->title }} // for title
{{ $p->body }} // for body and so on
@endforeach
@else
<p>Post are empty.</p>
@endif
您返回主刀片文件,但在 view.blade.php 文件中使用了 $post 變量。 在控制器中返回 view.blade.php 文件
$post = posts::all();
return view('view')->with(['post'=>$post]);
in cmd : php artisan make:model Posts
then check App/ Posts.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Posts extends Model
{
protected $table = 'posts';
protected $fillable = [
'title', 'body','category_id'
];
}
then in Controller
public function index()
{
$post = Posts::all();
return view('view',compact('post'));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.