前言
在上一篇,跟各位快速的實作完後台的介面,並且完成了Database中資料的新增、修改、刪除
接下來,就是要讓我們在後台的變更都可以直接影響到前台,將資料帶入到前台頁面當中~
建立前台Controller
首先來建立起Controller吧
方式跟後台的一樣,使用artisan make的指令來建立
php artisan make:controller Frontend\HomeController
php artisan make:controller Frontend\AboutController
php artisan make:controller Frontend\ProductController
php artisan make:controller Frontend\StoreController
建立完成了,在每個Controller內都加入
public function index () { //... }
然後在Controller最上方加入各自會使用到的Model
比較特別的是因為頁首頁尾網站標題每個頁面都使用得到,所以都會使用到Website的Model
use App\Models\Website;
另外Store也要特別注意,因為Store的前台頁面不知道為何也有About的內容XDD
所以StoreController除了Store, Website的Model外,也要加上About的Model唷!
取得資料回傳給前台
在各個index內,我們要取得需要的資料,送回前端
所以我們要這樣做:
HomeController
public function index () { $home = Home::find(1); $website = Website::find(1); return view('frontend.index', compact('home', 'website')); }
AboutController
public function index () { $about = About::find(1); $website = Website::find(1); return view('frontend.about', compact('about', 'website')); }
ProductController
public function index () { $products = Product::orderBy('id')->get(); $website = Website::find(1); return view('frontend.products', compact('products', 'website')); }
StoreController
public function index () { $store = Store::find(1); $website = Website::find(1); $about = About::find(1); return view('frontend.store', compact('store', 'website', 'about')); }
前台接資料囉
這邊也跟前一篇後台帶資料一樣
使用 {{ $val->col }}
以及 {!! $val->col !!}
(可以輸出帶有HTML結構的內容)
來顯示Controller交付的資料
像是
然後有一個比較特別,因為Product頁面它是有特別的style
奇數筆的標題在右,敘述在左,偶數筆的則相反
它之所以會有這樣排版的css class是
mr-auto // 靠左
ml-auto // 靠右
所以我們可以利用@if…@else的方式來判斷並產生對應的css class
另外要注意的,是Store頁面
由於我們存資料的時候,是使用time的格式,所以它還會有包含到秒
我們需要的格式是 00:00 AM 這樣
所以我們可以利用date()方法來幫助格式化時間
{{ date('g:i A', strtotime($store->sun_open)) }}
g: 小時,12小時制,01-12
i: 分鐘,00-59
A: 上午或下午,AM/PM
strtotime()可以幫助你將時間的string轉成date()會吃的格式XD
微調樣式
頁面都套好資料後,各位會發現因為原本這個網站是針對英文字體設計
所以中文字都會是預設的醜醜細明體(我覺得很醜啦XD)
所以我們可以加一個frontend.css,稍微調整一下字型等細節
body, h1, h2, h3 ,h4 ,h5, h6, p{ font-family: '微軟正黑體', -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol" !important; } .list-hours .list-hours-item { font-style: normal; }
這是我加的部分~
完成!
登登~
到這邊,整個網站就完成囉~
這是我加上資料後的樣子
一個很簡單的形象網站就出來囉
如果你想要客制化更多內容,可以在設計資料庫去增加資料表或欄位
從最初到現在,是不是很簡單呢~
Laravel初心者系列的教學就到這邊告一個段落
專案都放在Github上,大家可以去參考
https://github.com/chasewwy/laravel_tutorial
如果有任何問題也歡迎在下面留言~
我會盡力回答你們的問題~
See you!