<?php
namespace AppModels;
use IlluminateDatabaseEloquentModelNotFoundException;
use IlluminateSupportFacadesFile;
use SpatieYamlFrontMatterYamlFrontMatter;
class Post
{
public function __construct(
public string $title,
public string $excerpt,
public int $date,
public string $body,
public string $slug
){}
public static function all()
{
return cache()->rememberForever('posts.all', function () {
return collect(File::files(resource_path('posts')))
->map(fn ($file) => YamlFrontMatter::parseFile($file))
->map(fn ($doc) => new Post(
$doc->title,
$doc->excerpt,
$doc->date,
$doc->body(),
$doc->slug
))
->sortByDesc('date');
});
}
public static function find($slug)
{
return static::all()->firstWhere('slug', $slug);
}
public static function findOrFail($slug)
{
$post = static::find($slug);
if (! $post) {
throw new ModelNotFoundException();
}
return $post;
}
}