Show some code. We cannot possibly guess the error by a small description
Feb 22, 2022
12
Level 1
Blog tutorial
Good afternoon, Everybody! I am learning Laravel and I went through the tutorial and now I am a bit stuck, so in short I defined class Post and which has a function All and function Find. in both cases when I dd returns I get all the information I need, but then when I call my class Post::find($slug) from routes/web.php I return Null. Has anybody got any ideas?
namespace App\Models;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\File;
use Spatie\YamlFrontMatter\YamlFrontMatter;
use Illuminate\Support\Facades\Cache;
class Post
{
public $title;
public $slug;
public $date;
public $excerpt;
public $body;
public function __construct($title, $body, $date, $excerpt, $slug)
{
$this -> title = $title;
$this -> body = $body;
$this -> date = $date;
$this -> excerpt = $excerpt;
$this -> slug = $slug;
}
public static function all()
{
return cache()->rememberForever('posts', function() {
return collect(File::files(resource_path("posts")))
-> map(fn($file) => YamlFrontMatter::parseFile($file))
-> map(fn ($document) => new Post(
$document -> matter("title"),
$document -> body,
$document -> matter("date"),
$document -> matter("excerpt"),
$document -> matter("slug"),
))
-> sortByDesc('date');
});
}
public static function find($slug)
{
$posts = Post::all();
$posts -> firstWhere('slug', $slug);
}
}
use App\Models\Post;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\File;
Route::get('/', function () {
return view ('posts', [
'posts' => Post::all()
]);
});
Route::get('posts/{post}', function ($slug) {
dd(Post::find($slug));
return view ('post', [
'post' => Post::find($slug)
]);
})->where('post', '[A-z_\-]+');
Please or to participate in this conversation.