1

I have created a create form create.blade.php and a edit form edit.blade.php - both form fields are identical.

It quite annoying when I add new fields in the create.blade.php, I also need to add fields in edit.blade.php.

How can I merge into 1 blade file it so it work for both way for creating and editing (view via db).

For example in create.blade.php I have this:

<label>Name</label>
<input type="text" name="name" value="{{ old('name') }}">
@if ($errors->has('name'))
  <label class="error">{{ $errors->first('name') }}</label>
@endif

In edit.blade.php

<label>Name</label>
<input type="text" name="name" value="{{ old('name', $category->name) }}">
@if ($errors->has('name'))
  <label class="error">{{ $errors->first('name') }}</label>
@endif
I'll-Be-Back
  • 10,530
  • 37
  • 110
  • 213

3 Answers3

1

Just check if model exists:

{{ old('name', empty($category) ? '' : $category->name) }}

Also, you may want to check if it's create or update form and change form url accordingly:

{{ route(empty($category) ? 'article.create' : 'article.update' ) }}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • Is there a way to create like a helper method to do `{{ old('name', empty($category) ? '' : $category->name) }}` ? Something like `populate('name', 'category->name')` or similar? – I'll-Be-Back Jan 18 '17 at 11:11
  • Sure, why not? Please check this answer about [creating custom Laravel-like helpers](http://stackoverflow.com/a/37339565/1227923) – Alexey Mezenin Jan 18 '17 at 11:13
0
<input type="text" name="name" value="{{ $category ? $category->name : old('name') }}">
EddyTheDove
  • 12,979
  • 2
  • 37
  • 45
  • Although this code might solve the problem, adding a explanation helps op to understand why/how it works. – BDL Jan 18 '17 at 15:02
0

you can use a partial (fancy name for a smaller template) for your form, and pass that partial the data you require.

Using the example of a booking system:

In your create blade file:

@include('bookings._forms', ['booking' => new \App\Booking])

and the edit file ($booking being retrieved on the controller):

@include('bookings._forms', ['booking' => $booking])

And then your form partial can look like this:

<label for="name" class="label">Name</label>
        <input type="text"
                     class="input"
                     name="name" id="name"
                     placeholder="Guest name"
                     value="{{ old('name') ?? $booking->name }}">

The good thing with this method is that now you can have ONLY your form elements on the partial and only have to update 1 file when you add fields, AND the actual tag stays on your create and edit template, so no worries about that either.

Hope that's clear and it helps.