php-フォームを送信するときにモデルから新しいオブジェクトを作成する
このテンプレートを使用して、投票モデルの新しいインスタンスを作成します
{{ Form::model(new Poll, array('route' => 'create')) }}
{{ Form::label('topic', 'Topic:') }}
{{ Form::text('topic') }}
{{ Form::submit() }}
{{ Form::close() }}
これはモデルです
//models/Polls.php
class Poll extends Eloquent {}
これは移行です
//database/migrations/2014_03_16_182035_create_polls_table
class CreatePollsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('polls', function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('topic');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::drop('polls');
}
}
コントローラーでオブジェクトを作成するには、どのような手順を知っておく必要がありますか?
これは私が持っているものですが、フォームを投稿すると、500ステータスコードが返されます
//controllers/poll.php
class Poll extends BaseController {
public function index() {
return View::make('home');
}
public function create() {
$topic = Input::get('topic');
// if ($topic === "")
// return View::make('home');
$poll = Poll::create(array('topic' => $topic));
var_dump($poll);
return View::make('poll', array('poll' => $poll));
}
答え :
解決策:
まず、新しいモデルを作成するときに model binding を使用する必要はありませんが、ロードしようとしているときにのみ使用します。編集用のデータベースからの既存のモデルなので、
Form
は次のようになります。
@if(isset($ poll))
{{Form :: model($ poll、array('route' =>'update'、$ poll-> id))}}
@そうしないと
{{Form :: open(array('route' =>'create'))}}
@endif
{{Form :: label('topic'、'Topic:')}}
{{$ errors-> first('topic')}}
{{Form :: text('topic')}}
{{Form :: submit()}}
{{Form :: close()}}
コントローラーで、 create メソッドを使用して新しいモデルを作成するには、次のように試してください。
public function create(){
$ topic = Input :: get('topic');
$ rules = array('topic' =>'required');
$ validator = Validator :: make($ topic、$ rules);
if($ validator-> failed()){
Redirect :: back()-> withInput()-> withErrors();を返します。
}
そうしないと {
Poll :: create(array('topic' => $ topic));
Redirect :: action('Poll @index');を返します。
}
}
インデックス方式:
public function index()
{
$polls = Poll::all();
return View::make('home')->with('polls', $polls);
}
編集するために既存のTopicをロードする必要がある場合は、データベースからロードし、次のようなものを使用してフォームに渡すことができます(In {-code -8} クラス):
public function edit($ id)
{{
$ poll = Poll :: get($ id);
View :: make('poll'、array('poll' => $ poll));を返します。
}
Poll クラスの更新メソッド:
public function update($ id)
{{
//Pollを更新します。ここでid=$ id
//[email protected]にリダイレクトします
}
適切な方法を使用してルートを宣言します(createおよびUpdateには Route::post(...) を使用します)。ドキュメント、特に Route :: model()と Mass Assignment
。
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。