現在,要正式把控制器與資料庫連結起來。順便偷埋之後兩個主題☻。
引入所需使用的套件
首先,得先把之前建立好的Model引入。另外,我們在偷偷引入一個Illuminate\Support\Facades\Log
。
use Illuminate\Support\Facades\Log;
use App\BlogPost;
use Parsedown;
完成CRUD操作
Create / Store
public function store(Request $request)
{
$title = $request->input("titile", "未命名文章");
$content = $request->input("content");
$post = new BlogPost;
$post->title = $title;
$post->content = $content;
$post->save();
Log::info("Store New Blog Post: id = $post->id");
return redirect()->action(
'Blog\PostController@show', ['id' => $post->id]
);
}
可以透過Request
的input
方法,取得POST來的資料,還可以補上預設參數。這邊取得標題與內容後,建立一個新的PostBlog
實體存入資料庫。
Read / Show
public function show($id){
$post = BlogPost::find($id);
if(! $post){
abort(404);
}
$content = $post->content;
{
$Parsedown = new Parsedown();
$content = $Parsedown->text($content);
}
return view("blog.post", [
"title" => $post->titile,
"content" => $content,
]);
}
讀取與之前控制器的內容差不多。不同的是,需要先從資料庫尋找資料,如果找不到就回傳404找不到錯誤頁面。之後會對該頁面進行修改。現在http://localhost/blog/post/12 將會顯示404錯誤頁面,只有http://localhost/blog/post/1 才會出現之前填入的內容。