prgrm
prgrm

Reputation: 3833

Passing information to forms from databases in Laravel

In order to populate a form with information from a database, I do something like this:

@if($parameter_passed_in_the_controller)
<input type="text" value=@($parameter_passed_in_the_controller)></input>
@else
<input type="text" value=""></input>
@endif

While this works I wonder if there is other way to do in a less archaic way, or if this is actually the correct way to do this.

Upvotes: 1

Views: 26

Answers (3)

flynorc
flynorc

Reputation: 839

If you have some sort of CRUD going on, or in any case when you are fetching a model from database, you can use "form model binding".

A short tutorial here.

As explained in the tutorial you use the laravelcollective library and then create the form in such way

{!! Form::model($yourModel, ['action' => 'YourController@yourMethod']) !!}

    //here you can create fields like so
    <div class="form-group">
      {!! Form::label('field_name', 'Field label') !!}
      {!! Form::text('field_name', '', ['class' => 'form-control']) !!}
    </div>

{!! Form::close() !!}

What i like about this method is that it is also taking care of filling the form with "old" values in case of validation failure and such.

Upvotes: 1

Advaith
Advaith

Reputation: 2580

If the value given to the input is big then this is the correct way.

But if you are passing a variable or request, then you can use another way like this --

<input type="text" value={{ $parameter_passed_in_the_controller ? 'echo if it is true' : 'echo if it is false' }}></input>

? ends the if statement and : used for else

Upvotes: 1

Gayan
Gayan

Reputation: 3704

What I usually do is

@if($parameter_passed_in_the_controller)
<input type="text" value={{ $parameter_passed_in_the_controller }}></input>
@else
<input type="text" value=""></input>
@endif

Upvotes: 2

Related Questions