接著來整理一下 code,我們把內容從 class 讀過來:
Route::get('/post/{post}', function ($slug) {
$post=Post::find($slug);
return view('post', [
'post' => $post
]);
});
有了 Post:: 之後 Laravel 會去 app/Models 找 Post 的 class,所以我們要在裡面建立一個 Post.php 的檔案,程式內容如下:
namespace App\Models;
class Post
{
}
接著要在 web.php 這支最上面讀入 Model
use App\Models\Post;
接著因為要讀 Post 裡面的 function,所以我們要在裡面加上這段,這樣就可以根據變數讀出不同的 html:
public static function find($slug){
$path = resource_path("views/post/{$slug}.html");
$post = file_get_contents($path);
return $post;
}
這樣我們輸入網址就可以看到跟之前一樣的內容了:http://localhost/post/first
html 的內容參考這篇文章
一樣我們可以加上判斷檔案是否存在,不存在就顯示 404:
public static function find($slug){
$path = resource_path("views/post/{$slug}.html");
if(!file_exists($path)){
abort(404);
}
$post = file_get_contents($path);
return $post;
}
接著我們在 posts 那頁把所有相關的 html 檔案讀進來:
Route::get('/posts', function () {
$post=Post::all();
return view('posts', [
"posts"=>$post
]);
});
接著這時我們就要在 Post 裡新增一個 function all(),要做的就是把 post 資料夾裡的所有檔案讀出來:
public static function all(){
return File::files(resource_path("views/post/"));
}
做到這邊只是讀取檔案,我們還要把內容讀取出來,所以改成這樣:
public static function all(){
$files= File::files(resource_path("views/post/"));
return array_map(function($file){
return $file->getContents();
}, $files);
}
最後我們就在 posts.blade.php 裡把資料顯示出來:
<?php foreach($posts as $post): ?>
<?=$post?>
<?php endforeach; ?>