异常消息:未定义的变量:

I'm trying to retrieve data from mysql database using laravel. It shows error 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 code

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

I expect it to show result for my database table but it shows error Undefined variable

you returning home blade file but using $post variable in view.blade.php file. return view.blade.php file in controller

 $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'));
        }

First go to project folder via cmd then,

php artisan make:model Posts.

You will get created file in App folder with the name Posts.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
    protected $table   = 'posts';

    protected $fillable = [
        'title', 'body','category_id'
    ];
}

Don't forget to include namespace of your model at the top of your controller like:

use App\Posts;

and then in your index method,

public function index()
{
    $post = Posts::all();

    return view('your_views_correct_path',compact('post'));
}

Don't need to pass your post collection by converting it to array to view. Simply pass post as shown above. Then you can easily access post attribute by looping post collection in foreach loop.

@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