首页 > 解决方案 > 在 laravel 8 的第 4 行(“日期:2021-06-27”附近)的未引用映射值中不能使用冒号

问题描述

我正在尝试从一些 HTML 页面中获取数据并按照本教程将它们显示到视图中:https ://laracasts.com/series/laravel-8-from-scratch/episodes/12?page=2 这里我使用从 my-forth-post.html 获取数据的 YAML 前端

这是我的模型 Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
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(function ($file){
            return $file->getContents();
        },$files);
    }
    public static function find($slug)
    {
        if (!file_exists($path = resource_path("posts/{$slug}.html"))) {
            throw new ModelNotFoundException();
        }

        return cache()->remember("posts.{$slug}", 1200, function () use ($path) {
            return file_get_contents($path);
        });
    }
}

这是 web.php

<?php

use App\Models\Post;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Route;
use Spatie\YamlFrontMatter\YamlFrontMatter;


Route::get('/', function () {
    $files = File::files(resource_path("posts"));

    $posts = array_map(function($file){
        $document = YamlFrontMatter::parseFile($file);

        return new Post(
            $document ->title,
            $document ->excerpt,
            $document ->date,
            $document ->body(),
            $document -> slug
       );
    },$files);
    
    return view('posts',[
        'posts' => $posts
    ]);
});

Route::get('post/{post}',function($slug){
    $post = Post::find($slug);
    return view('post',[
        'post' => $post
    ]);
})->where('post','[A-z_/-]+');

这是 my-forth-post.html

---
title: This is forth page
slug: my-forth-post
excerpt: fasdlkfjsdjk
date: 2021-06-30
---
<p>
    What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen
    book it has?
</p>

标签: laravellaravel-8

解决方案


删除空间

标题:这是第四页 slug:my-forth-post 摘录:fasdlkfjsdjk 日期:2021-06-30


推荐阅读