![](/img/trans.png)
[英]Need to prevent new page from opening up when submitting a PHP $_POST form.
[英]Creating a new object from a model when submitting a form
我有这个模板来创建我的投票模型的新实例
{{ 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
,而仅在试图从数据库中加载现有模型进行编辑时才需要使用model binding
,因此Form
应该是这样的:
@if(isset($poll))
{{ Form::model($poll, array('route' => 'update', $poll->id)) }}
@else
{{ Form::open(array('route' => 'create')) }}
@endif
{{ Form::label('topic', 'Topic:') }}
{{ $errors->first('topic') }}
{{ Form::text('topic') }}
{{ Form::submit() }}
{{ Form::close() }}
在您的控制器中,要在使用create
方法时create
新模型,请尝试如下操作:
public function create() {
$topic = Input::get('topic');
$rules = array('topic' => 'required');
$validator = Validator::make($topic, $rules);
if($validator->fails()) {
return Redirect::back()->withInput()->withErrors();
}
else {
Poll::create(array('topic' => $topic));
return Redirect::action('Poll@index');
}
}
索引方法:
public function index()
{
$polls = Poll::all();
return View::make('home')->with('polls', $polls);
}
当您需要加载现有的Topic
进行编辑时,可以使用以下方法从数据库中加载Topic
并将其传递给表单(在Poll
类中):
public function edit($id)
{
$poll = Poll::get($id);
return View::make('poll', array('poll' => $poll));
}
Poll
类中的更新方法:
public function update($id)
{
// Update the Poll where id = $id
// Redirect to Poll@index
}
使用适当的方法声明路由(使用Route::post(...)
进行创建和更新)。 阅读更多有关文档,特别是Route :: model()以及有关Mass Assignment
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.