0

I installed the spatie/yaml-front-matter package into my Laravel project to access metadata in my HTML files. Unfortunately, I cannot sort the files by date because the date property in the metadata is returning a null value. My operating system is Microsoft Windows 10 Pro Version 10.0.19042 Build 19042. I am using Laravel version 9 and PHP Version 8.0.

Here's a copy of the metadata as it appears at the top of my HTML files.

---

title: My Fifth Post
slug: my-fifth-post
excerpt: Lorem Ipsum is simply dummy text of the printing and typesetting industry.
date: 2022-01-25

---

Below is a copy of the POST class in my Models directory.

namespace App\Models;

use Illuminate\Support\Facades\File;
use Spatie\YamlFrontMatter\YamlFrontMatter;

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()
    {
        return collect(File::files(resource_path("posts")))
            ->map(fn($file) => YamlFrontMatter::parseFile($file))
            ->map(fn($document) => new Post(
                $document->title,
                $document->excerpt,
                $document->date,
                $document->body(),
                $document->slug
            ));
    }

    public static function find($slug)
    {
        return static::all()->firstWhere('slug', $slug);
    }
}

Finally, a screenshot of a var_dump(Post::find('my-fifth-post')).

enter image description here

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
  • I think you mixed Laravel Model with your controller. You should inherit from Laravel's default Model: use Illuminate\Database\Eloquent\Model; and class Post extends Model. After that you can use Laravel's model methods casts etc. You have find, all methods in Model and it is not ideal. You can use repository pattern if you like. Laravel, Eloquent uses active record so you do not have to set all $title $slug etc. Laravel does it all. – gguney Feb 21 '22 at 14:09
  • 1
    Thank you, gguney, for your response. I applied your recommendations, and I now have the desired behavior. – R. Purcell Feb 23 '22 at 15:22

1 Answers1

0

You should inherit from Laravel's default Model:

use Illuminate\Database\Eloquent\Model; 

and class Post extends Model. After that you can use Laravel's model methods casts etc. You have find, all methods in Model and it is not ideal. You can use repository pattern if you like. Laravel, Eloquent uses active record so you do not have to set all $title $slug etc. Laravel does it all

gguney
  • 2,512
  • 1
  • 12
  • 26