Laravel 學習筆記 — 專案練習 Part 2 — 文章功能

ViNciHsu
Oct 18, 2020

--

構思簡易的文章架構

Model:Article

  • title:string
  • content:text
  • state:['draft' (草稿階段),'published' (已發布)]
  • user_id:integer (對應 User Model 的 id 欄位)
  • deleted_at:datetime

開始建立 Model

php artisan make:model Article -m (m表示請 artisan 幫我們建一個 migration 出來)

依照剛剛的構思,建立資料表的結構,確認之後,執行 php artisan migrate

建立資料表的結構

enum() 內的陣列,表示之後填寫改欄位的狀態不是 draft 或 published 其中一個時,就會跳錯誤

SQLite 查看創建好的資料表結構

MVC 結構,Model 建完來建 controller,執行 php artisan make:controller ArticlesController

接下來需要建立 Route

覺得 resource 內太長的話,可以將其寫到 use

原本寫法

查看目前的 route ,因為剛才有做會員系統,所以很亂,這邊可以挑出 article 單獨查看其 resource 幫忙建立的幾個路由;由於我 php artisan route:list | grep article 指令無效,只好先截影片的圖

圖片來自於高見龍的影片,連結:https://www.youtube.com/watch?v=kEtG7_GaBwA&ab_channel=%E9%AB%98%E8%A6%8B%E9%BE%8D

設定首頁,這裡多用了 name('root') 之後如果提到 root 就會指向首頁

目前啟動 php artisan serve 會出現以下錯誤是正常的,因為

  1. ArticlesController 內也沒有 function index() 相關程式編寫
  2. 還沒有設置 view 的頁面
function index() 相關程式編寫
view(‘articles.index’)

到 views\layouts\article.blade.php 建個檔案做 layout

回到 resource\views\articles\index.blade.php 編寫(檔案自行創建),再到網頁上看,就有"文章列表"的字樣了

有”文章列表”的字樣

至於為何 class 可以使用 font-thin,是因為剛安裝 jetstream 時,系統已經有安裝一包 CSS,在 resource\views\layouts\article.blade.php 中,有引用 public\css\app.css ,注意此處不是引用 resource\css\app.css,而是引用打包過後的 public\css\app.css 檔案

最後,因為"文章列表"的字樣很貼邊邊,因此加個樣式,在 resource\views\layouts\article.blade.php 中加 class <main class="m-4">

--

--

No responses yet