Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

laravel Post model for flat file CMS

<?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;
    }
}
Source by laracasts.com #
 
PREVIOUS NEXT
Tagged: #laravel #Post #model #flat #file #CMS
ADD COMMENT
Topic
Name
6+3 =