I have this template to create a new instance of my Poll model
{{ Form::model(new Poll, array('route' => 'create')) }}
{{ Form::label('topic', 'Topic:') }}
{{ Form::text('topic') }}
{{ Form::submit() }}
{{ Form::close() }}
This is the model
//models/Polls.php
class Poll extends Eloquent {}
This is the migration
//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');
}
}
What steps do I need to do know to build my object in the controller?
This is what I have, but when I post the form, it returns a 500 Status Code
//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));
}
First of all you don't need to use model binding
when you are creating a new model but only when you are trying to load an existing model from database for editing so the Form
should be something like this:
@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() }}
In your controller, for creating a new model when using create
method, try it like this:
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');
}
}
Index method:
public function index()
{
$polls = Poll::all();
return View::make('home')->with('polls', $polls);
}
When you need to load an existing Topic
to edit, you may load it from database and pass it to the form using something like this (In Poll
class):
public function edit($id)
{
$poll = Poll::get($id);
return View::make('poll', array('poll' => $poll));
}
The update method in the Poll
class:
public function update($id)
{
// Update the Poll where id = $id
// Redirect to Poll@index
}
Declare the routes using proper methods (Use Route::post(...)
for create and Update). Read more on documentation and specially the Route::model() and also about Mass Assignment
.