壹、目錄及代辦事項
Table of Contents
待學習項目
貳、Routing
一、Routing 的用途與設定的方法
1. 段落的語意
二、Veiw - Blade / CSS / JS
1. View 的運作方式與 Blade 簡介
a. View 存放在 resource/views 的資料夾裡面,檔名後面的 .blade.php 可以省略不寫

b. 如果在 views 資料夾裡面還有分資料夾,可以使用 . 來呼叫

2. Blade 的 layout 設定方式
blade 是 Laravel 創建的 template 系統,專門用來做 layout 的,用來將 controller 和 view 分開。

a. @yield 與 @section:
用 title 指定名稱,後面塞要放的字串

用 content 指定名稱,晝面塞要放進去的 p 段落

b. @section/@show 與 @section/@endsection
@section/@show 在 Html 挖出一個空間,然後右側的 section 的 @parent 代表 'This is master sidebar' 這段文字,可以透過移動 @parent 的位置來決定文字的排序

3. Blade 的程式控制
a. @if @elseif @else @endif
b. @unless @endunless
除非 Auth 有 check,不然會顯示沒有登入
c. Switch Statements
d. Loop
- @foreach @endforeach
檢視 $user 在 $users 中是否為空
- @forelse @empty @endforeelse
檢視 $user 在 $users 中是否為空,如果是就跳轉到 @empty,如果不是就將印 - 出來
e. @continu @break
- 使用 @continu 或 @break 來略過或停止迴圈
- 另外也可以更精簡的寫法,把 @continue 和 @break 寫在判斷式裡
f. The Loop Variable
loop 的相關變數使用

- 當有巢狀迴圈時,可以透過 parent 取得上面一層的迴圈變數
4. Blade 的資料顯示與 component
a. 資料顯示
使用雙花括弧{{ $variable }}包住變數要顯示的變數名稱
b. component & slot
- 在 @component() 裡面寫上指定的 component 名稱

- component 在雙花括弧 {{ $slot }} 內挖空可以插入 Html

- 在 component 中挖空雙花括號 {{ $title }},在 views 中如果有使用到 component,就可以使用 @slot('title') @endslot 插入。
- 而 {{ $slot }} 就對應到沒有指定名稱的字串

c. include subview
使用 include 做成 subview 精簡程式碼

5. CSS 與 JS 設定
a. 放置路徑
- Develop
- /resource/sass
- /resource/js
––––––– npm run watch ––––––
b. 使用 npm install 安裝所需的套件
c. 在使用 npm run watch 監控生成 public
d. 最後路徑

6. Laravel Mix
使用 Laravel Mix 自動 compile
三、實作靜態頁面
1. 開始的準備
做出 index 的頁面
- 新增 resource/route/index.blade.php
- 執行 php artisan serve 跑 serve
2. 套版 - 基本架構
- js/css 的路徑:使用絕對路徑 /css/app.scss

如果使用相對路徑 css/app.scss,Laravel 的讀取路徑會使用相對於
去做讀取檔案,假如這個 Route 是
他就會從網址路徑下 http://127.0.0.1:8000/foo/bar/css/app.css 去找 css 檔,就會找不到。
3. layout 調整
- 將固定的內容(header、footer)使用 @include 繼承
- 其中畫面會改變的部分(page-title、hero、content) 使用 @yield 呼叫
4. about 頁面製作
- 因為 header 的部分在 about 頁面有些許不同。因此需要使用 @isset 去判斷,如果 @include 有傳入 $overlay 變數
,就顯示 l-header_overlay
- 另外的狀況是,有 overlay 的變數和沒有 overlay 的變數分別使用不同 class 名稱
- $overlay 變數的設定:
- 只有在 index 的頁面需要出現 overlay 的變數,因此在 @extend 加上 overlay 的變數為 true
-
- 在 layout/app.blade.php 裡面 header 的 @include 做 overlay 的變數判斷
5. 導覽列 - 顯示登入後連結
- 使用 request 去看目前的 path 在哪,如果在該分頁就使他 active
request 用法連結
到 storage/laravel.log 看 log
六、 Database - migration/ model
1. Model 簡介 / 資料庫連結
a. 連結資料庫
- 檔案路徑: config/database.php
- 檔案內的路徑指到 .env,打開 .env,下面這一段就是要設定的地方
b. 連接 mysql 資料庫
c. migration 建立欄位
- migration 檔案程式碼的撰寫
撰寫 migration 要寫 up 和 down,up 是新增 table,down 是刪除 table
4. migration 的操作
A. Table
- Schema
- create: 建立 table
- rename: 更改 table 名稱
- drop: 丟掉 table
- dropifExists: 確定有這個 table 才丟掉
- table: 進入原本已經有的 table,去更改內容
- Table Name 命名
- Blueprint $table 的 function 去接 table,之後就可以用 $table 去建立欄位或 index
B. Columns
決定"名字"和"型態"
- column 的型態
- integer
- boolean
- string: 字串
- text: 長字串
- enum: (Admin Manager Member)
- data/ dateTime/ time: 記錄日期/ 日期時間/ 時間
- json
- Increments(UNSIGNED BIGINT): 用在id
- timestamp(created_at/ updated_at): 建立資料時間/ 更新時間
- unsignedInteger: fori
- softDeltes(deleted_at): 刪除的時候其實是更新時間
更多型態參考
C. Indexes
5. 常見的 table 型態
6. column 的 Modifier
- nullable
- after 可以決定在放哪個 column 後面
- default 預設值
- useCurrent 如果沒有給他值,他會給你現在的時間戳記
- unsigned 如果希望與 user_table 做連結,可以改成 unsigned
- comment 為欄位做註記
7.migration 修改/刪除欄位
安裝 package: 用於判別 Database 的狀態如何,配合所需修改,提供適合的 sql 語法。
composer require doctrine/dbal
去修改原本就存在的 column,使用 Schema::table
去新增欄位一樣使用,Schema::table,不過是去新增一個原本不在的名稱
修改欄位的名稱,Laravel 的 renameColumn 不支援型態為 enum 的名稱,如果要修改,要全部刪除再新增
- Dropping Columns
丟棄 column
- dropRemenberToken (remember_token)
- dropSoftDeletes(deletd_at): 有點像 display:none 將這筆 column 隱藏掉
- dropTimestamps(created_at/ updated_at)
8. migration 索引 (indexes)
a. Indexes
-
建立索引的時機
-
建立複合式的索引,丟進一個陣列
$table->index(['account_id', 'created_id'])
-
指定索引的名稱,如果不指定 Laravel 會幫你命名
$table->unique('email', 'unique_')
-
建立索引的方法有
- primary
- 適用情境:用來明確識別在資料當中的每一筆資料,是不同的資料。每筆資料的主鍵不能重複
- 例如:每一個排班紀錄都有一個不重複的流水號(CleanScheduleId)
- unique
- 適用情境:資料不能重複的欄位,可以接受 NULL 值。
- 例如:家庭成員的手機號碼,可以設定為UNIQUE
- index
- 適用情境:設定在常用來當作查詢條件的欄位
- 目的:藉由資料庫的演算法提高查詢速度
- 成本:占用額外的磁碟空間
- 舉例:家事排班表的打掃日期,經常被拿來當作查詢統計的條件
b. Drop Indexes
- Drop 索引的方法有
- dropPrimary: $table->dropPrimary('users_id_primary');
- dropUnique: $table->dropUnique('users_email_unique');
- dropIndex: $table->dropIndex('geo_state_index');
以上方法要指定這個 index 的名稱。
如果不想指定名稱可以使用 dropIndex(['陣列1'])
9. Foreign Key
- 使用情境:
在 posts 裡面的 user_id 要去和 users 的 id 做連結
- 延伸狀況:
如果使用者被刪除了,那使用者所寫的文章怎麼辦?
- artisan migrate:rollback
要刪除 migration 前,foreign key 可能已經和其他 table 建立連結了,所以要先刪除 foreign key
- 更新的因應方式 ON UPDATE
- ON UPADTE RESTRICT (defalt) :same as RESTRICT if you try to update a company_id in table COMPANY the engine will reject the operation if one USER at least links on this company.
- ON UPDATE NO ACTION : same as RESTRICT
- ON UPDATE CASCADE : the best one usually : if you update a company_id in a row of table COMPANY the engine will update it accordingly on all USER rows referencing this COMPANY (but no triggers activated on USER table, warning). The engine will track the changes for you, it's good.
- ON UPDATE SET NULL : if you update a company_id in a row of table COMPANY the engine will set related USERs company_id to NULL (should be available in USER company_id field). I cannot see any interesting thing to do with that on an update, but I may be wrong.
- 刪除的因應方式 ON DELETE
- ON DELETE RESTRICT (defalt) : 必須 posts 都已經刪除,user 才能刪除
- ON DELETE NO ACTION : 要刪除作者直接可以刪,不過文章會留著
- ON DELETE CASCADE : user 刪除,文章一起刪
- ON DELETE SET NULL : 刪除作者後,會將刪除的作者變成 NULL
10. migration 演練
-
建立一個 migration
php artisan make:migration create_posts_table
-
跑 migration
php artisan migrate
-
回朔 migration
php artisan migrate:rollback
11. Model
建立 model 指令
php artisan make:model Post
Eloquent
- ActiveRecord
- ORM(Object Relation Mapping)

- Active Record Pattern
CRUS/getter/setter/properties/etc.
Model -> table
Model -> model(relationships)
Validation
OOP style query
Convention > config 慣例大於設定
12. 生成 Model
建立 model 指令
php artisan make:model post
建立 model 指令連帶 migrate
php artisan make:model post –migration 或
php artisan make:model post -m
b. 修改 Primary keys
c. 不紀錄 timestamps
d. 修改到別的 database
13. Eloquent 取得多筆資料(retrieving models)
- Additional Constraints
query builder(where/ orderBy/ take/…)
get
- Refreshing Model
- freash(): 不會更新自身的資料,只會再拿一次資料,並且把他指派給另一個變數
- collections : 類似 array, 就是一堆資料的集合
- Chunking Result
可以使用 chunk 指定特定數量,處理完之後再抓資料
14. Eloquent 取得單筆資料(Retrieving Single Model)
- Not Found Exceptions 如果找不到的狀況
- Aggregates
15. Eloquent 新增 & 更新資料 (insert & update)
- save 一次插入或更新一筆資料
- Mass Update 一次更新多筆資料
- Mass Assignment 一次將全部資料放進 model
得到這些使用者的資料

可以使用全部丟進去的方法
更簡化的做法
使用時機: 使用者填完表單後 submit 出去,可以用all() 來接收全部資料

:warning: 注意可能發生的安全性的問題
使用 fillable / guarded 來確認哪一筆資料可以直接放進來 / 不可以放進來,兩個完全相反,不會同時使用
16. Eloquent 刪除 modal
- Delete Models Query
找到符合需求的資料,一次刪除
- Soft Delete
做資料標記。並不是真的刪除
a. 在 migration 出 softDelete 的欄位
b. modal
c. 執行 Soft Delete 和 Delete 動作一樣,但因為前面的設置,會執行 Soft Delete,主要去看有沒有 Delete_at 的時間戳記,有就是有 soft Delete
d. Querying Soft Deleted Models
17. Eloquent 取得常用資料
- Query Scopes - Local Scopes
只想選取固定範圍的資料可以使用,使用 Scopes

例如: 只想選取有 active 的資料
- model 中先新增 Query Scopes,注意,query 名字一定要 scope 開頭
- 使用 Query
- Dynamic Scopes
加入變數來控制 Scope

找到 type 等於 admin 的 scopes
- Comparing Models
使用 is,如果這個東西是這個東西的話…
18. Query Builder 建立 Query 的工具
a. 介紹
- Query Builder 可以提供給其他 class 使用 (Eloquent)
- 可以與 php 完美融合
- 安全性佳
b. 工具介紹
官網連結
19. relationship
兩個 table 間的關係,例:小明和小明寫的文章的關係

a. 建立 relation 的順序
a. migration 建立 foreign key
b. Eloquent Model 定義彼此的關連性
c. 實際使用
傳統上分兩次取用資料,一次找小明,另一次找文章
如果已經建立 foregin key
b. relation 的關係

雙邊設定:每個使用者都有一個隱私權設定
雙邊設定:隱私權是使用者的一部分
Use: 可以透過 user 去找到他的隱私權設定
Use: 也可以透過隱私權去找到他的 user
- One To Many

雙邊設定: 每篇文章有很多留言
雙邊設定: 留言是屬於這篇文章的
- Many To Many
- 多對多需要一個第三個表格來記錄 post 與 tag 的關係,第三個的表格命名為 post_tag,順序以英文字母順序擺放,
- id 名稱應命名為 post_id 與 tag_id

雙邊設定: 這篇 post 是屬於這些 tags 的
雙邊設定: 這個 tag 是屬於這些 posts 的
Use
如果不使用預設名稱,可以透過下列方法更改 post_tag, post_id, post_tag 為 post_tag_refs, my_post_id, my_tag_id
20. 取得關聯式資料 (Query relations)
在 Model 定義完後,做關聯資料的取得
a. Query Method: 可以接 query builder 去做其他處理
b. Dynamic property: 無法接 query builder 去做其他處理
c. Querying Relationship Existence 如果你有
d. Querying Relationship Absence 如果你沒有
- 使用 withCount 會多一個 table名稱 + _count 的屬性
21. 關聯式資料的讀取方式(Lazy & Eager loading)
a. Lazy Loading
在使用 query 時,如果是 Lazy Loading,在每一次的 foreach 都得去跟資料庫要一次資料。這會太耗效能
b. Eager Loading
- 使用 Eager Loading 在第一次就去資料庫把需要的資料拿出來,這樣 foreach 就只會在 php 裡面跑,不用每次都跑回資料庫。
八、 Controller
route 可以指派 controller 內的 method 做特定行為,可以使 route 裡面比較乾淨
1. 建立 Controller 指令
a. Router 與 Controller 對應
- Router
去抓 postController 裡面的 show
b. 在 Controller 內使用 model
c. Return JSON
前端單純只需要資料,可以回傳 JSON 資料就好
d. Return nothing
2. 注入參數 (method injection)
a. controller 使用 $request 全部接收
$name = $request->name; 的 name 會等於 $_REQUEST['name'] 等於將 request 的全部資料放在這
如果只要特定的 post 或 get 可以將 name 改成
$_POST['name']
$_GET['name']
b. URL + parameter
- 當 route 使用 {id} 傳值到 controller 裡面
可以在 function 後寫 $id 接收參數
c. URL + 變數
可以在 function 後寫 model 接收參數
3. CRUD 的好幫手:resource
a. 自動加上 CRUD 的 method
b. 建立加上 model 的 coontroller
c. 自動加上 CRUD 的 method

d. Routes 對應的設定
4. MVC 總結
a. 只需回傳一個 view 回去

b. 透過 controller 執行內容再透過 view 印出東西

c. 透過 controller 使用 model 去資料庫拿東西

九、實作 CURD
使用 http 來做 destory post
- 做一個隱藏的 form,在 input 裡面使用 delete method
- 記得 form 要加上 csrf token
- 按下刪除按鈕時執行 js 替換掉 action 的路徑,然後再送出
使用 ajax 來做 destory post
- 在 header 加上 meta csrf 的 token
- 在 resource/app.js global 的環境,將 ajax 設定成帶 csrf 參數
- 按下刪除按鈕時執行 js,將 ajax 帶上 delete 的方法,之後 reload 頁面
十、Authentication
1. 簡介
使用下面指令產生 Authentication
2. 使用方法
a. Protecting Routes
- 使用 middleware 檢查使用者是否有登入,如果沒有登入就會被踢出去,如果有就會執行 function 內的內容
- 如果整個 controller 的每個 method 都需要驗證可以寫在 controller 的 construct 裡面
b. 取得使用者資訊
c. 未登入導向頁面
路徑: app/Http/Middleware/Authenticate.php
3. make:auth
指令
4. middleware protect
5. 加上 user_id
- 使用 migration 加上原本被刪除的 user_id
6. post 紀錄 user_id
$post->user->name
十一、Mail
1. 簡介
php 也有內建信件系統,不過會很常被當成垃圾信件。
這邊建議可以使用
dev: mailtrap
release: mailgun
十二、Validation
laravel Validation
1. 驗證機制
a. HTTP 流程

驗證成功->存入資料庫
驗證失敗->產生錯誤訊息->將錯誤訊息帶回上一個 view
- 在 method 執行前先做 validation 驗證。


b. AJAX 流程
2. 驗證設定
a. 撰寫驗證邏輯
如果沒有加上 bail 的話,required、unique、max 三個錯誤訊息都會產生

加上 bail 只要有一個驗證沒通過,即會產生錯誤訊息,後面的動作就不會再去驗證


- trimStrings/ ConvertEmptyStringsToNull
如果是空字串,將會被清掉變成 null,
以下方為例,publish_at 是一個 Option 的設定,因為空字串會被轉為 null,因此要加上 nullable 的設定。免得產生額外錯誤。

3. 印出錯誤訊息
使用 * 將 attachment 裡面巢狀陣列的所有屬性的錯誤都取出來
4. 自訂錯誤訊息
將錯誤訊息定義好後,丟到 $validator 的 $message
$rule => 錯誤訊息
將驗證的表單分離出來,原本是寫在 method 裡面去做驗證

分離出來 StoreBlogPost,在 $request 前就做驗證了

- 使用指令產生 Form Request Validation
產生的檔案會放在 app/Http/Requests/StoreBlogPost.
將原本驗證的資訊寫在 rules

6. 自訂驗證條件
a. Use Rule Object
指令
驗證文字是否為大寫

引用 Custom Validation Rules 需要用 array 方式把值傳入

b. Use Closure