I have a form in which there is a textarea field, on page load, it will fetch the detail from a table, (for the first time it will show blank as first time there is no record in table), there is an update button which is used to insert value of that field in database, after that page will get reload and i will get the value in that field from database, when i again change the value of that field, clicked on update button, it should update the value of that field in database and fetch that detail from database,
So how can i use same controller on that update button to first insert value in database and then update value in database?
You can use firstOrNew(array $condition)
to get first hit result or new instance of model.
After that set the submitted data to the instance and save the instance by save()
method.
public class SomeController {
public function createOrUpdateData() {
$data = Model::firstOrNew(['someColumn' => $condition]);
// Set the model attribute from submitted data
$data->save();
return Redirect::back();
}
}
In your POST function before redirecting to the get route retrieve the id of the newly created record and pass it to the view. If the data is empty then pass a null value which will be accessible on your text input which you can then retrieve from the next POST function. Something like this:
// Controller
public function getIndex()
{
$data = Model::first();
if ($data)
{
$value = $data->column_that_you_need;
}
else
{
$value = "";
}
return View::make('your.view', compact('value'));
}
public function postIndex()
{
// validate
$post = new Model;
$post->column = Input::get('your_input');
$post->save;
return Redirect::to('/your_route_for_index');
}
// your view
<input type="text" value="{{{$value}}}"/>