35
loading...
This website collects cookies to deliver better user experience
Post
model class and move the post finding code from the route definition to the Mode class method find()
. We add another method all()
to this class where we fetch all posts from the resource/posts
directory. We use the Laravel File Facades Illuminate\Support\Facades\File
fetch all the files from a directory into an array. Route::get('/posts/{post}', function ($slug) {
$path = __DIR__."/../resources/posts/{$slug}.html";
if(! file_exists($path)) {
abort(404);
}
$post = cache()->remember('posts'.$slug, 1200, fn() => file_get_contents($path));
return view('post', [
'post' => $post
]);
})->where('post', '[a-z\-]+');
Route::get('/posts/{post}', function ($slug) {
return view('post', [
'post' => Post::find($slug)
]);
})->where('post', '[a-z\-]+');
---
title: "My First Post"
slug: my-first-post
excerpt: Lorem Ipsum is simply dummy text of the printing and typesetting industry.
date: 2021-12-01
---
"spatie/yaml-front-matter": "^2.0"
and installed it. We can use this to parse a file like this:$document = \Spatie\YamlFrontMatter\YamlFrontMatter::parseFile($file_path);
$title = $document->title;
$body = $document->body();
sortBy()
to sort our posts by the published date.collect(SOME_ARRAY)->sortBy(FIELD_NAME)
php artisan tinker
>>
tinker>> cache(KEY_NAME)
will print the cached contenttinker>> cache()->forget(KEY_NAME)
will clear the cache for the specified keytinker>> cache(KEY_NAME)
is same as tinker>> cache()->get(KEY_NAME)
tinker>> cache(['KEY' => val])
is same as tinker>> cache()->put('KEY', val)
tinker>> cache(['KEY' => val], now()->addSeconds(3))
will cache and remember the key for three seconds
storage/framework/views
directory..blade.php
. If you omit the .blade
extension, your PHP code will be still executed but your blade syntax will be not resolved.{{ $title }}
is identical to <?PHP echo $title; ?>
@foreach($posts as $post)
{{ $post->title }}
@endforeach
<?php
foreach($posts as $post):
echo $post->title;
endforeach;
?>
@if() ... @endif
block{{ $post->body }}
will escape the p tags or any other HTML. You can prevent this by this syntax {!! $post->body !!}
but be careful and not use this with user supplied input like form submissions.
@unless
, @dd
, and the $loop
variable
the $loop
variable gives us information about the current iteration of the loop:
{#295 ▼
+"iteration": 1
+"index": 0
+"remaining": 4
+"count": 5
+"first": true
+"last": false
+"odd": true
+"even": false
+"depth": 1
+"parent": null
}