Home > Article > PHP Framework > Handle Form forms gracefully in Laravel
When developing Laravel applications, it usually involves form processing. Regarding how to elegantly process and reuse Laravel's Form forms, the following is a small life experience:
Use Form Package
Although writing native HTML code is indeed more readable, in fact Form Package will still bring us a lot of convenience, such as using Form::model() and Form::select().
Imagine an example: we need to add or update a user's username
We can design a code and directory structure similar to this:
// 位于 resources/views/users/edit.blade.php {!! Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'put']) !!} @include('users._form') // Your cancel / update buttons {!! Form::close() !!} // 位于 resources/views/users/_form.blade.php <div class="form-group"> {!! Form::label('name', 'Name') !!} {!! Form::text('name') !!} </div>
The HTML generated by the above Form The code probably looks like this:
<form method="POST" action="http://example.com/users/1" accept-charset="UTF-8"> <input name="_token" type="hidden" value="Q5oILhAr92pVqfE0ZSSXjSdJuUi09DVSPWweHQlq"> <input name="_method" type="hidden" value="PUT"> <div class="form-group"> <label for="name">Name</label> <input name="name" type="text" value="Michael"> </div> </form>
Note that in the Form::model() method, we pass the $user variable, which means: if $user has a value of the name attribute, the form will This value is automatically filled in without us having to write it manually.
The second point is that since we are passing $user to Form::model(), we can use this little trick in the controller:
class UserController extends Controller { public function create() { return view('users.create', ['user' => new User]); } public function edit(User $user) { return view('users.edit', ['user' => $user]); } }
In this case, you There will be no conflict when editing and adding. There is a name value when editing and updating, but there is no need for a name value when adding. So we can write the entire Form like this:
// 位于 resources/views/users/_form.blade.php <div class="form-group"> <label for="name">Name</label> <input type="text" name="name" value="{{ old('name', $user->name) }}" class="form-control"> </div>
And you’re done!
Finally
It’s still the same sentence: You can still consider Form Package when processing forms, especially when you are processing
For more Laravel related technical articles, please visit the Laravel Framework Getting Started Tutorial column to learn!
The above is the detailed content of Handle Form forms gracefully in Laravel. For more information, please follow other related articles on the PHP Chinese website!