0

我正在使用 MySQL (XAMPP) 数据库,该数据库已链接到我的 Laravel 文件夹的 .env 文件中。我正在尝试使用数据库在 posts.index 页面上显示“博客文章”,并且在 Visual Studio 代码中没有显示任何错误,但是当我在浏览器中转到该页面时,它会显示此错误:

找不到错误类“app\Models\BlogPost” http://laravel.test/posts

帖子控制器

class PostsController extends Controller
{
    public function index()
    {
        return view('posts.index', ['posts' => BlogPost::all()]);
    }

    public function show($id)
    {
        // abort_if(!isset($this->posts[$id]), 404);

        return view('posts.show', ['post' => BlogPost::findorFail($id)]);
    }
}

博文模型

class BlogPost extends Model
{
    use HasFactory;
}

更新:我现在遇到的问题是我看到了 item 数组。(我是 Laravel 初学者,所以我并不总是在代码中看到问题)。

这是 post.index 代码:

@extends('layouts.app')

@section('title', 'Blog Posts')

@section('content')
{{--  @each('posts.partials.post', $posts, 'post')  --}}
@dd($posts)
@forelse ($posts as $key => $post)
    @include('posts.partials.post', [])
     @empty
     No posts found!    
    @endforelse
@endsection

这是我在浏览器中看到的(而不是数据库中的)

  #items: array:1 [▼
    0 => App\Models\BlogPost {#1233 ▼
      #connection: "mysql"
      #table: "blog_posts"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      +preventsLazyLoading: false
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #escapeWhenCastingToString: false
      #attributes: array:5 [▶]
      #original: array:5 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #attributeCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }
  ]
  #escapeWhenCastingToString: false
}
4

2 回答 2

0

这是因为@dd($posts)在刀片中使用。只需删除@dd($posts).

于 2022-02-17T06:40:21.447 回答
0

你的代码看起来不错。可能是 BlogPost 模型中的命名空间有问题。

如果您在 PostsController 控制器中将此代码用于类别模型:

使用 App\Models\BlogPost ;那么你的 BlogPost 模型本身就有这个命名空间

命名空间应用\模型;检查您的模型命名空间是否仍然存在。

于 2022-02-17T05:33:28.193 回答