【发布时间】:2021-12-25 22:53:21
【问题描述】:
我正在学习 Laravel,所以对此了解不多。我正在开发一个博客并面临一个问题。我还没有使用数据库,只是在练习硬编码文件。 问题是当我单击链接打开帖子时,页面显示“为 foreach() 提供的参数无效(视图:C:\wamp64\www\blogapp\resources\views\posts.blade.php)”。 在主页上,我检查了帖子是否不是数组,但它显示您的帖子是数组。这是我的代码: web.php
Route::get('/', function () {
$files = File::files(resource_path("posts"));
$posts = [];
foreach ($files as $file) {
$document = YamlFrontMatter::parseFile($file);
$posts[] = new Post(
$document->title,
$document->excerpt,
$document->date,
$document->body(),
$document->slug
);
}
return view('posts', [
'posts' => $posts,
]);
});
Route::get('posts/{post}', function ($slug) {
return view('posts', [
'posts' => Post::find($slug),
]);
})->where('posts', '[A-z\-]+');
后模型: Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\File;
class Post
{
public $title;
public $excerpt;
public $date;
public $body;
public $slug;
public function __construct($title, $excerpt, $date, $body, $slug)
{
$this->title = $title;
$this->excerpt = $excerpt;
$this->date = $date;
$this->body = $body;
$this->slug = $slug;
}
public static function all()
{
$files = File::files(resource_path("posts/"));
return array_map(fn($file) => $file->getContents(), $files);
}
public static function find($slug)
{
if (!file_exists($path = resource_path("posts/{$slug}.html"))) {
// return redirect('/');
throw new ModelNotFoundException();
}
return cache()->remember("posts.{$slug}", 5, fn() => file_get_contents($path));
}
}
我的观点:posts.blade.php
<body>
@if (is_array($posts) || is_object($posts))
@foreach ($posts as $post)
<article>
<h1>
<a href="/posts/{!! $post->slug !!}">
{!! $post->title !!}
</a>
</h1>
<div>{!! $post->excerpt !!}</div>
</article>
@endforeach
@else
<h3>
{{ 'Not An Array or Object' }}
<br>
</h3>
@endif
</body>
在资源文件夹中,我有一个名为 posts 的文件夹,其中包含 4 个 HTML 文件,HTML 代码为: 我的第一个帖子.html
---
title: My First Post
slug: my-first-post
excerpt: Lorem ipsum dolor sit amet consectetur adipisicing elit.
date: 2021-10-06
---
<p>
1. Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero
blanditiis hic, fugiat molestias nostrum at autem ipsam minima sint, earum
explicabo accusamus magni quasi. Laborum dignissimos voluptas ea deserunt
voluptatum.
</p>
不知道问题出在哪里,请帮忙
【问题讨论】:
-
你可以使用
dd()helper 来调试这个 -
我做了...在 web.php 中,它告诉我
$posts是一个数组。但是当我将它传递给刀片时,它应该是一个数组,但它不是。所以我在刀片中使用了ddd(),它告诉我它是一个字符串。
标签: php laravel model-view-controller eloquent model