Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto populate "Form::text" from "Form::model" after adding extra attribute(class) in Laravel

I am currently rendering and populating a form in laravel using the laravelcollective plugin. this is working as expected:

{!! Form::model($user, ['action' => 'user@updateUser']) !!}

<div class="form-group">
    {!! Form::label('user_name', 'Name') !!}
    {!! Form::text('user_name') !!}
</div>

<button class="btn btn-success" type="submit">Update</button>

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

The above code generates the form and populates the input field with the user's name.

If I want to add a class attribute to the form input like so:

{!! Form::text('user_name', '', ['class' => 'form-control']) !!}

It does not populate the input value because in theory I've set the default value (second parameter) to ''.

Is there a way of populating the value and adding a class without explicitly doing so like this:

{!! Form::text('user_name', $user->user_name, ['class' => 'form-control']) !!}

By doing the above it defeats the object of rendering the form via a model {!! Form::model($user, ['action' => 'user@updateUser']) !!} as I may as well parse the $user as a variable onto the template, which I don't want to do.

like image 831
steve Avatar asked Nov 08 '22 05:11

steve


1 Answers

Then you can use null instead "" blank

{!! Form::text('user_name', null , ['class' => 'form-control']) !!}

You can also use old function

{!! Form::text('user_name', $user->user_name or old('user_name'), ['class' => 'form-control']) !!}

This $user->user_name or old('user_name') can be expressed as

If $user->user_name is exist then put value of $user->user_name otherwise check for old input which is "" blank first time and have some value if you redirect back if any error comes.

or simply use isset method or in php 7 use $user->user_name ?? ''

{!! Form::text('user_name', $user->user_name ?? '', ['class' => 'form-control']) !!}
like image 124
Niklesh Raut Avatar answered Nov 14 '22 23:11

Niklesh Raut