BigJobbies
BigJobbies

Reputation: 193

Laravel 4 - Showing edit form with OLD data input as well as DB information

Im making a edit form for my app and i was wondering if someone could tell me how to get the data from the database into my text field.

I can locate the record i need to edit based on the users click, and i can display the information if i do the following:

value="{{ $letter->subject }}"

BUT, the problem im having is that when i run it through the validation and there is an error, it comes back with the database information instead of the OLD data.

So my questions is. Is there a way to serve up the database information first and then when it goes through the validatior, validate the information the user has edited?

Currently to validate the text field and bring the data back incase of error, im using

Input::old('subject')

Is there a parameter for that old bit that allows me to put in the DB data?

Cheers,

Upvotes: 3

Views: 8570

Answers (4)

ikurcubic
ikurcubic

Reputation: 2289

I'm not sure for Laravel 4 but in Laravel 5, function old takes second param, default value if no old data in session.

Please check this answer Best practice to show old value

Upvotes: 0

Nadeem0035
Nadeem0035

Reputation: 3957

Make it more simple and clean

<input type="text" name="subject" value="{{ (Input::old('subject')) ?: $letter->subject }}">

Upvotes: 3

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

All you need is form model binding http://laravel.com/docs/html#form-model-binding:

{{ Form::model($letter, ['route' => ['letters.update', $letter->id], 'method' => 'put']) }}
   // your fields like:
   {{ Form::text('someName', null, ['class' => 'someHTMLclass' ...]) }}
   // no default values like Input::old or $letter->something!
{{ Form::close() }}

This way you form will be populated by the $letter data (passed from the controller for example).

Now, if you have on your countroller:

// in case of invalid data
return Redirect::back()->withInput();

then on the redirect your form will be repopulated with input values first, not the original model data.

Upvotes: 7

Igor R.
Igor R.

Reputation: 897

Hey you could validate and return ->withInput() and then in your actual form, check if there is Input::old() and display it, otherwise display from the db.

example:

<input type="text" name="subject" 
value="{{ (Input::old('subject')) ? Input::old('subject') : $letter->subject }}">

Or you could go the other way and define the variable and do a regular if statement, instead of the ternary one! Up to you to decide what you want to use!

Upvotes: 10

Related Questions