laravel5.2架構裡,預設不帶form模組,所以需要自己安裝,參考:from模組安裝
在路由裡面添加新的路由app/Http/routes.php
Route::get('/articles','ArticlesController@index');Route::get('/articles/create','ArticlesController@create');//因為下面的{id}能夠傳入所有作為id的參數到show方法,所以需要先將create路由放在他的上面,這樣在訪問的時候,會優先匹配create路由,然後再到下面的Route::get('/articles/{id}','ArticlesController@show');Route::post('/articles/store','ArticlesController@store');//使用一個post路由,這個路由是為了處理create頁面提交過來的表單的
在controller裡面添加新的controllerapp/Http/Controllers/ArticlesController.php
public function create(){ // create方法,指向create.blade.php, return view('articles.create'); } public function store(Request $requests){ //store方法是接受create頁面提交的資料的處理方法,這個Request $requests是注入執行個體,需要在頁面use這個類Illuminate\Http\Request $input = $requests->all(); //擷取request請求的所有資料 $input['publish_at']=Carbon::now(); Articles::create($input);//通過create方法寫入資料庫 return redirect('/articles'); //寫入後重新導向到首頁 }
resources/views/articles/create.blade.php
@extends('layout.app')@section('content') {!! Form::open(array('url' => '/articles/store')) !!} //form表單提交的地址就是我們store路由 {!! Form::label('title', 'Title:') !!} {!! Form::text('title', null, ['class' => 'form-control']) !!} {!! Form::label('content','content:') !!} {!! Form::textarea('content',null,['class'=>'form-control']) !!} {!! Form::submit('submit',['class'=>'btn btn-primary form-control']) !!} //這些都是laravelcollective html 和form模組的使用方法//{!! !!}是blade引擎的寫法,主要是為了防止代碼直接被解析為html,詳情參考https://laravel.com/docs/5.2/blade {!! Form::close() !!}@stop
這是對應的html模板源碼
< !DOCTYPE html> Laravel
本文由 PeterYuan 創作,採用 署名-非商業性使用 2.5 中國大陸 進行許可。 轉載、引用前需聯絡作者,並署名作者且註明文章出處。神一樣的少年 »Laravel Forms 使用