【问题标题】:Exception message: Undefined variable:异常消息:未定义的变量:
【发布时间】:2019-07-24 05:31:09
【问题描述】:

我正在尝试使用 laravel 从 mysql 数据库中检索数据。它显示错误undefined variable

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

postController 代码

 public function index()
    {
        $post = posts::all()->toArray();
        return view('view',compact('post'));
    }

我希望它显示我的数据库表的结果,但它显示错误 Undefined variable

【问题讨论】:

  • $post的回报是什么?
  • 未定义变量:post(查看:D:\xampp\htdocs\app3\resources\views\view.blade.php)
  • 你确定帖子是模特
  • 我没明白你的意思
  • posts 是不是你的模特?

标签: php mysql laravel


【解决方案1】:

先通过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 循环中循环帖子集合来轻松访问帖子属性。

@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

【讨论】:

    【解决方案2】:
    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'));
            }
    

    【讨论】:

    • 检查你的控制器、路由和 view.blade.php
    • 并尝试 dd($post);在 $post = posts::get(); 之后是否显示所有数据
    【解决方案3】:

    您返回 home 刀片文件,但在 view.blade.php 文件中使用 $post 变量。 在控制器中返回 view.blade.php 文件

     $post = posts::all();
        return view('view')->with(['post'=>$post]);
    

    【讨论】:

    • 现在我正在返回视图刀片,但问题仍然存在
    • addLoop($__currentLoopData); foreach($__currentLoopData as $row): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
    • dd($post);我认为它是空的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 2021-12-28
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多