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

时间:2014-03-16 19:38:09

标签: php forms laravel laravel-4 eloquent

我有这个模板来创建我的民意调查模型的新实例

{{ 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));
    }

1 个答案:

答案 0 :(得分:1)

首先,在创建新模型时不需要使用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