> 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/form.md).

# 使用 Form

現在該是讓使用者和網站互動的時候了，使用者可以透過表單來新增資料或查詢資料等等。使用 Laravel Bland 提供的 Form 類別，可以非常簡單快速的製作表單。

## 建立表單

開啟 app/views/home.blade.php，修改如下：

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

要產生表單，首先要有 open() 及 close()，其他元件則放在其中。

常用元件：

* label：用來顯示一段文字，通常放在文字輸入框之前，用以說明。
* text：單行文字輸入框。
* textarea：多行文字輸入框。
* submit：執行送出的按鈕。

還有其他許多元件，之後用到再說明。

open() 方法的參數是一個陣列，第一個 url 表示要將資料送到哪個網址去處理。第二個 method 預設是 post，所以除非有要使用其他方法傳遞資料，可以省略不寫。使用 post 通常用來 新增資料；put 用來更新資料；delete 則用來刪除資料。

## 送出表單

接下要把表單的資料送進資料庫。當使用者按下 submit 按鈕時，會將資料以指定的方法(post)傳送到指定的位址(URI)，我們必須設定 route 來處理這筆資料。

開啟 app/routes.php，加入：

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

因為我們在表單中使用 post 方法傳送，所以要接收表單送過來的資料，要使用 Route::post() 方法。接著要求 HomeController 的 store() 方法來處理，所以在 HomeController 中新增一個 store() 方法，如下：

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

    $post = new Post;
    $post->title = $input['title'];//方法一
    $post->content = Input::get('content');//方法二
    $post->save();

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

Input 類別可以讓你處理從表單傳送過來的資料，你可以在一開始使用 Input::all() 來取得所資料，以陣列的方式儲存。然後以 $input\['title'] 陣列取值的方法，取得欄位的資料(方法一)。或是使用 Input::get('content') 的方式，直接取得欄位的值(方法二)。

使用前一節所說的，以 Model 的方式新增資料到資料庫。最後使用 Redirect::to('/') 方法，轉向首頁。

去查看資料庫是否已新增了一筆資料。
