> For the complete documentation index, see [llms.txt](https://tony915.gitbook.io/laravel-4-2/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tony915.gitbook.io/laravel-4-2/begining/project-mini-blog.md).

# 第一個小專案：迷你部落格

綜合前面說到的內容，就可以開始來寫我們的第一個小專案：迷你部格格。

先來描述一下功能：

* A.首頁：顯示文章的標題清單。
* B.文章標題：點選可開啟文章內容。
* C.新增功能：點選後開啟表單頁面來新增內容。
* D.編輯功能：在標題後方，點選後開啟表單頁面編輯內容。
* E.刪除功能：顯示在編輯頁面中，點選後刪除內容。

開始動手。

## A.首頁：顯示文章的標題清單

### 1.設定 Route

編輯 app/routes.php

```
Route::get('post', 'HomeController@index');
```

對應網址：

```
http://localhost/blog/public/post
```

### 2.設定 Controller

編輯 app/controllers/HomeController.php

```
public function index()
{
    $posts = Post::all();

    return View::make('home')
        ->with('title', 'My Blog')
        ->with('posts', $posts);
}
```

利用 Post Model 取得全部文章，回傳值會是一個陣列，所以我們的變數名稱以複數表示 $posts。最後傳送給 view 去顯示，view 的名稱是 home。

### 3.設定 View

編輯 app/views/home.blade.php

```
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ $title }}</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    <div>{{ link_to('post/create', '新增') }}</div>
    @if (isset($posts))
        <ol>
        @foreach ($posts as $post)
            <li>{{ link_to('post/'.$post->id, $post->title) }}
            ({{ link_to('post/'.$post->id.'/edit', '編輯') }})</li>
        @endforeach
        </ol>
    @endif
</body>
</html>
```

@if ... @endif 是 Blade 樣板系統的 if 語法；@foreach ... @endforeach 則是 foreach 迴圈，最終會被轉換成 PHP。

使用  來顯示資料。使用 foreach 迴圈，逐一取出 $posts 陣列中的資料。

```
link_to('連結位址', '顯示的文字');
```

會被轉換成 HTML 中的 a 連結標籤。

### 4.完成

Route、Controller、Model、View 全都完成，可以來執行看看這個熱騰騰的網站了。當你新增一筆資料後，看起來會像這樣：

![](/files/-M49T0gcXU2rNaRuTn8V)

我們來讓"新增"的功能可以動作。

## B.文章標題：點選可開啟文章內容。

文章的標題被點選後，會開啟一個頁面來顯示文章的內容。

### 1.設定 Route

編輯 app/routes.php

```
Route::get('post/{id}', 'HomeController@show');
```

對應網址：

```
http://localhost/blog/public/post/123
```

123 假設為文章 id。

### 2.設定 Controller

編輯 app/controllers/HomeController.php

```
public function show($id)
{
    $post = Post::find($id);

    return View::make('show')
        ->with('title', 'My Blog - '. $post->title)
        ->with('post', $post);
}
```

### 3.設定 View

新增 app/views/show\.blade.php

```
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ $title }}</title>
</head>
<body>
    @if (isset($post))
        <h1>{{ $post->title }}</h1>
        <p>{{ $post->content }}</p>
    @endif

    {{ link_to(URL::previous(), '回上一頁') }}
</body>
</html>
```

最後面我們加了一個"回上一頁"的連結，使用 URL 類別來產生網址。

### 4.完成

點選首頁中文章清單的標題，會顯示該文章的內容，結果畫面：

![](/files/-M49T7_uMdCvSFpmnPLP)

## C.新增功能：點選後開啟表單頁面來新增內容

在首頁中，點選\[新增]連結，開啟新增頁面，送出內容後，返回首頁。

### 1.設定 Route

編輯 app/routes.php

```
Route::get('post/create', 'HomeController@create');
```

對應網址：

```
http://localhost/blog/public/post/create
```

### 2.設定 Controller

編輯 app/controllers/HomeController.php

```
public function create()
{
    return View::make('create')
            ->with('title', '新增文章');
}
```

新增一個 create() 方法，回傳一個 view 名稱為 create，這個 view 會有一個表單來新增文章。

### 3.設定 View

新增 app/views/create.blade.php

```
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ $title }}</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    {{Form::open(['url'=>'post', 'method'=>'post'])}}
    {{Form::label('title', '標題')}}<br>
    {{Form::text('title')}}<br>
    {{Form::label('content', '內容')}}<br>
    {{Form::textarea('content')}}<br>
    {{Form::submit('發表文章')}}
    {{Form::close()}}
</body>
</html>
```

這裡不要搞混了 url 和 method 的值，雖然都是 post，但一個是我們命名的網址名稱，一個則是 submit 時要使用的資料傳送方法。

### 4.前端部份完成

到目前為止，我們完成了前端這部份，結果畫面：

![](/files/-M49TNK7tBxzOjuYcqDg)

接下來要來處理後端的部份，將取得表單資料並儲存到資料庫。

### 5.設定 Route

編輯 app/routes.php

```
Route::post('post', 'HomeController@store');
```

這裡的 Route::post 是指 method；'post'則是 url。

### 6.設定 Controller

編輯 app/controllers/HomeController.php

```
public function store()
{
    $input = Input::all();

    $post = new Post;
    $post->title = $input['title'];
    $post->content = $input['content'];
    $post->save();

    return Redirect::to('post');
}
```

使用 Input 類別來取得表單資料。因為是新增資料，所以先 new 一個 Post 物件出來，接著將值指定給 $post 的屬性，最後 save() 就新增到資料庫了。

最後使用 Redirect::to('post') 導向首頁。這時首頁就會顯示剛才新增的文章標題。

## D.編輯功能：在標題後方，點選後開啟表單頁面編輯內容

編輯的連結被放置在文章標題後方，點選後開啟頁面來編輯。

### 1.設定 Route

編輯 app/routes.php

```
Route::get('post/{id}/edit', 'HomeController@edit');
```

對應網址：

```
http://localhost/blog/public/post/123/edit
```

123 假設為文章 id。

### 2.設定 Controller

編輯 app/controllers/HomeController.php

```
public function edit($id)
{
    $post = Post::find($id);

    return View::make('edit')
            ->with('title', '編輯文章')
            ->with('post', $post);
}
```

使用 $id 找到這篇文章，將它送給 view。

### 3.設定 View

新增 app/views/edit.blade.php

```
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ $title }}</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    {{Form::open(['url'=>'post/'.$post->id, 'method'=>'put'])}}
    {{Form::label('title', '標題')}}<br>
    {{Form::text('title', $post->title)}}<br>
    {{Form::label('content', '內容')}}<br>
    {{Form::textarea('content', $post->content)}}<br>
    {{Form::submit('儲存')}}
    {{Form::close()}}
</body>
</html>
```

這裡和 create.blade.php 大同小異，但要注意 Form::open() 的參數：

* url 改為 'post/id' 的型式，id 就是 Post 物件的 id 屬性。
* form 的 method 要改成 put，表示由不同的 route 處理。

Form::text 及 Form::textarea 的第二個參數要給值，值就是從資料庫取出的資料。

### 4.前端部份完成

到目前為止，我們完成了編輯前端的部份，結果畫面：

![](/files/-M49Too5_6F8b-4tU0bf)

接著就是設定後端來儲存資料。

### 5.設定 Route

編輯 app/routes.php

```
Route::put('post/{id}', 'HomeController@update');
```

你會看到這個 route 和顯示文章內容的很像，但是這裡要用 put ，而不是 get，要注意。

### 6.設定 Controller

編輯 app/controllers/HomeController.php

```
public function update($id)
{
    $input = Input::all();

    $post = Post::find($id);
    $post->title = $input['title'];
    $post->content = $input['content'];
    $post->save();

    return Redirect::to('post');
}
```

在 update($id) 方法中，使用 Post::find($id) 去找出這筆資料，並重新指定內容，save() 後就會對資料庫送出更新的動作。

快要完成了，目前什麼都有，就是不能刪除，把它加入吧～

## E.刪除功能：顯示在編輯頁面中，點選後刪除內容

### 1.設定 Route

編輯 app/routes.php

```
Route::delete('post/{id}', 'HomeController@destroy');
```

### 2.設定 Controller

編輯 app/controllers/HomeController.php

```
public function destroy($id)
{
    $post = Post::find($id);
    $post->delete();

    return Redirect::to('post');
}
```

一樣，先找到這筆資料，然後刪除。

### 3.設定 View

編輯 app/views/edit.blade.php

刪除的做法有點麻煩，要用到表單以 delete 型式來送出。把它加在原有表單後後面：

```
...略
<br>
{{ Form::open(['url'=>'post/'.$post->id, 'method'=>'delete']) }}
    <button type="submit">刪除</button>
{{ Form::close() }}
```

現在你已經可以刪除內容了。

## 總結

一路寫下來，你會發現 Route -> Controller (Model) -> View 這樣的開發流程，所以只要一直重覆這個流程，功能就會慢慢完成。Laravel 框架的各個部份各司其職，每個部份所付的責任清清楚楚，不僅開發容易、迅速，在日後的維護上也不會陷入混亂。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tony915.gitbook.io/laravel-4-2/begining/project-mini-blog.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
