Laravel 5 :(3)SEO Friendly URLs

Laravel 範例實作

此筆記主要紀錄學習以下 Laravel 的範例教學

Laravel 範例

實作 SEO URLs

先定義網址路徑

1
2
3
4
5
6
7
8
9
10
11
12
13
/                       index                   顯示首頁
/products products 顯示產品頁面
/products/details/{id} product_details(id) 顯示詳細產品頁面
/products/category product_categories 顯示產品分類
/products/brands product_brands 顯示產品品牌
/blog blog 顯示部落格
/blog/post/{id} blog_post{id} 顯示部落格文章
/contact-us contact_us 顯示聯絡我們
/login login 登入頁面
/logout logout 登出頁面
/cart cart 顯示購物車
/checkout checkout 結帳
/search/{query} search 顯示搜尋結果

建立 controller

複習流程如下(RCV)

1
2
3
4
-> HTTP 請求 
-> Route 處理 (看網址找 controller & funcrion )
-> Controller 處理 (可用 artisan 建立)
-> (可選) 呼叫 view

首先建立新的 controller

1
php artisan make:controller Front

修改/app/Http/Controllers/Front.php如下

主要就只是回傳網址對應的字串而已

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Front extends Controller {

public function index() {
return 'index page';
}

public function products() {
return 'products page';
}

public function product_details($id) {
return 'product details page';
}

public function product_categories() {
return 'product categories page';
}

public function product_brands() {
return 'product brands page';
}

public function blog() {
return 'blog page';
}

public function blog_post($id) {
return 'blog post page';
}

public function contact_us() {
return 'contact us page';
}

public function login() {
return 'login page';
}

public function logout() {
return 'logout page';
}

public function cart() {
return 'cart page';
}

public function checkout() {
return 'checkout page';
}

public function search($query) {
return "$query search page";
}
}

修改路由

/app/Http/routes.php修改如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/','Front@index');
Route::get('/products','Front@products');
Route::get('/products/details/{id}','Front@product_details');
Route::get('/products/categories','Front@product_categories');
Route::get('/products/brands','Front@product_brands');
Route::get('/blog','Front@blog');
Route::get('/blog/post/{id}','Front@blog_post');
Route::get('/contact-us','Front@contact_us');
Route::get('/login','Front@login');
Route::get('/logout','Front@logout');
Route::get('/cart','Front@cart');
Route::get('/checkout','Front@checkout');
Route::get('/search/{query}','Front@search');