在提交表单时从模型创建新对象


Creating a new object from a model when submitting a form

我有这个模板来创建我的Poll模型的新实例

{{ 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)) }}
@else
{{ 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->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进行编辑时,您可以从数据库中加载它,并使用如下方式将其传递给表单(在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