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
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' ) }}
<input type="text" name="name" value="{{ $category ? $category->name : old('name') }}">
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.
Related
I have a form with 4 input fields, all of them to which I applied an old() function so whenever users load the page after submitting the form, the data that they filled in would retain in the fields for better UX.
My issue is that out of these 4 fields, only 1 has the old() function working. The difference between this field and the others is that:
The name and id attributes for this field are the same, while other fields have different names and IDs respectively.
The input type for this field is type="number" while the other fields are type="text".
Based on these differences, I tried modifying the code to standardize them, and only one solution works which is that I change the input types to "number", however, not all my inputs are numbers, so it is not an ideal solution.
Form blade file:
<div class="form-group mb-3">
<input type="text" class="form-control" name="emp_name" id="company_name"
value="{{ old('emp_name' , (isset($user->emp_detail->emp_name) ? $user->emp_detail->emp_name : old('emp_name')) ) }}">
#if ($errors->has('emp_name'))
<span class="text-danger">{{ $errors->first('emp_name') }}</span>
#endif
</div>
<div class="form-group mb-3">
<input type="number" class="form-control" name="emp_length" id="emp_length"
value="{{ old('emp_length' , (isset($user->emp_detail->emp_length) ? $user->emp_detail->emp_length : old('emp_length')) ) }}">
#if ($errors->has('emp_length'))
<span class="text-danger">{{ $errors->first('emp_length') }}</span>
#endif
</div>
<div class="form-group mb-3">
<input type="text" class="form-control money-prefix" name="emp_monthly_gross_salary" id="monthly_salary"
value="{{ old('emp_monthly_gross_salary' , (isset($user->emp_detail->emp_monthly_gross_salary) ? $user->emp_detail->emp_monthly_gross_salary : old('emp_monthly_gross_salary')) ) }}">
#if ($errors->has('emp_monthly_gross_salary'))
<span class="text-danger">{{ $errors->first('emp_monthly_gross_salary') }}</span>
#endif
</div>
<div class="form-group mb-3">
<input type="text" class="form-control money-prefix" name="monthly_allowance" id="bonus"
value="{{ old('monthly_allowance' , (isset($user->emp_detail->emp_monthly_allowance) ? $user->emp_detail->emp_monthly_allowance : old('monthly_allowance')) ) }}">
#if ($errors->has('monthly_allowance'))
<span class="text-danger">{{ $errors->first('monthly_allowance') }}</span>
#endif
</div>
To be clear, I also have several other forms in which I applied the same old() function, with texts as well as numbers, and they work fine, so I am unsure why the old() function won't work on this form specifically. I also dd() the variables I wanted to output as the old function, so I am sure my controller is already passing the values, my blade just isn't showing it.
Can anyone advise me on this problem?
maybe the issue is the default value, may be set but empty
try to check it with old directly without the default value
ex:
replace
{{ old('emp_name' , (isset($user->emp_detail->emp_name) ? $user->emp_detail->emp_name : old('emp_name')) ) }}
with
{{ old('emp_name') }}
if it works fine with you then you need to enhance the default value condition
ie: (isset($user->emp_detail->emp_name) ? $user->emp_detail->emp_name : old('emp_name')
I´m traying to create form to create event.
i have one resourceRoute in my laravel 7. But when i send my form, return this message:
The POST method is not supported for this route
but how i said i have a resource route, and i call to method create.
My routes
Route::resource('calendario', 'CalendarioController');
My form:
div class="col-xs-12 p-5">
<form action="{{ Request::is('calendario/*/edit') ? route('calendario.update', $event->id) : route('calendario.create') }}" method="post">
#csrf
#if(Route::currentRouteName() == 'calendario.edit')
#method('PUT')
#endif
<div class="form-group">
<label for="nombre">Nombre</label>
<input type="text" class="form-control" name="nombre" id="nombre" value="{{ isset($event) ? $event->nombre : old('nombre') }}" aria-describedby="emailHelp" placeholder="Nombre del cliente">
</div>
<div class="form-group">
<label for="fecha-inicio">Fecha Inicio</label>
<input type="text" value="{{ isset($event) ? $event->fecha_inicio : old('fecha_inicio') }}" class="form-control" name="fecha_inicio" id="fecha-inicio">
</div>
<div class="form-group">
<label for="fecha-inicio">Fecha Fin</label>
<input type="text" value="{{ isset($event) ? $event->fecha_fin : old('fecha_fin') }}" class="form-control" name="fecha_fin" id="fecha-fin">
</div>
<input type="submit" class="btn btn-info" value="{{ Request::is('calendario/*/edit') ? 'Guardar' : 'Crear Cita' }}">
</form>
</div>
</div>
</div>
thsi form it´s used also for edit event and in edit i can ok... I don´t understand that i´m doing wrong
Thanks you for help
This is 100% an issue with the Route::resource('calendario', 'CalendarioController')
The update method accepts put as I can remember.
As you can see here: put/patch
So you can change your form method to method="put" or your have to define your routes like this: Route::post('path/{id}', 'CalendarioController#update')
I have a basic CRUD structure for a model that works well. Now I want to redirect to the create method and populate the form with a pre-existing model. It would work by a user selecting an id and then I would select that model and redirect to the create page and populate the form.
This is what I have tried so far
$order = Orders::find($id);
$inventory = Inventory::where(['id' => $order->inventory_id])->first()->toArray();
return redirect()->route('backend.inventory.create', $inventory['bag_id'])->withInput($inventory);
In the above example, it finds the order and selects the single inventory item related to it (I have confirmed that it's definitely selecting an inventory item as expected) and redirects to the inventory creation page. However, when using the ->withInput() method this doesn't seem to populate my form with the data as I expected.
How do I pass data to a form using a redirect?
Adding the form code as requested below. This is just one column of the form as its a huge block of code
<div class="form-group row" id="item-name" v-if="type != '3'">
<label for="name" class="col-md-2 col-form-label text-md-right">Item Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required>
#if ($errors->has('name'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
You can use this :
return Redirect::back()->withInput(Input::all());
If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.
Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests:
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
try this
<div class="form-group row" id="item-name" v-if="type != '3'">
<label for="name" class="col-md-2 col-form-label text-md-right">Item Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') ?? $inventory['name'] }}" required>
#if ($errors->has('name'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
{{ old('name') ?? ($inventory['name'] ?? '') }} if old data is present it will show old data otherwise $inventory->name which is coming from withInput with is also optional that's why i put ??
ref link https://laravel.com/docs/6.x/requests#old-input
You can use compact() function that creates array containing variables and their values.
$order = Orders::find($id);
$inventory = Inventory::where(['id' => $order->inventory_id])->first()->toArray();
return view('backend.inventory.create', compact('inventory'));
In your view page you can use it like,
<input id="name" type="text" class="form-control" name="name" value="{{ $inventory['name'] }}" required>
I have a controller called ItemController. With this controller, the method store and index are the only recognized methods. when i use the method update, it throws an error
Missing required parameters for [Route: items.update]
Route.php
Route::resource('items', 'ItemsController');
ResourceRegistrar.php
protected $resourceDefaults = ['index', 'create', 'store', 'show', 'edit', 'update', 'destroy'];
html
<form role="form" method="post" action="{{ route('items.update') }}">
{!! csrf_field() !!}
<div class="form-group" style="width: 400px;">
<label for="exampleInputPassword1">Item Name</label>
<input type="text" class="form-control" id="exampleInputPassword1" name="name" value="{!! $item->name !!}" placeholder="item name" required="">
</div>
<div class="form-group" style="width: 400px;">
<label for="exampleInputPassword1">Retail Price</label>
<input type="number" step="any" class="form-control" id="exampleInputPassword1" value="{!! $item->retail_price !!}" name="retail_price" placeholder="retail price" required="">
</div>
<div class="form-group" style="width: 400px;">
<label for="exampleInputPassword1">Quantity Price</label>
<input type="number" step="any" class="form-control" id="exampleInputPassword1" value="{!! $item->quantity_price !!}" name="quantity_price"
placeholder="quantity price " required="">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Controller
public function update(Request $request, $id)
{
$item = Item::findorFail($id);
$item->name = $request->get('name');
$item->retail_price = $request->get('retail_price');
$item->quantity_price = $request->get('quantity_price');
$item->update($request, $id);
Session()->flash('flash_message', 'Item successfully updated');
return redirect()->route('items.index');
}
How is this happening?
When you call items.update route it expects the item you are updating, but you are not passing that item in the request, so the route throws an error because you are missing a required item to be able to know which one you are updating, does this make sense?
EDIT:
you need to include $item->id in your route('items.update', $item->id)
You need to be including a route parameter for the item you are updating. If you run
php artisan route:list
you should see something like: /items/{item} App\Http\Controllers\ItemController.
Your request URL should include the item id like:
`/items/1`
where 1 is the primary key for the item updating.
edit
You need to pass id to the route helper method in your HTML form:
action="{{ route('items.update', $item->id) }}"
Also, in your form, set the method as PUT or PATCH by:
<form>
{!! method_field('put') !!}
//or
{!! method_field('patch') !!}
...
</form>
Laravel uses a technique called Form Method Spoofing to fake PUT, PATCH, and DELETE HTTP verbs via POST.
edit 2
You're saving the record incorrectly, change
$item->update($request, $id);
to
$item->save();
I have a controller TourCategoryController.php and has edit method:
public function edit(TCategory $tCategory)
{
return view('admin.manage.tour.category.edit')->withCategory($tCategory);
}
And below is the code from my view edit:
<div class="col-sm-4">
{{Form::model($category,['route' => ['tour-category.update', $category->id ], 'method' => "PUT"]) }}
<input type="text" class="form-control" id="name" name="name">
<label for="name">Name</label>
{{ Form::close() }}
</div>
The trouble I'm having is, the input field is not being filled with form modal binding.
While inspecting the edit form action attribute shows action="http://localhost:8000/manage/tour-category" while it should be like action="http://localhost:8000/manage/tour-category/{id}"
Route for the controller:
Route::prefix('manage')
->middleware('role:superadministrator|administrator|user')
->group(function () {
Route::resource('tour-category','TourCategoryController');
});
Use laravel text field instead of plain form text field.
{{ Form::text('name',null,['class'=>'form-control','id'=>'name']) }}
If you are not using Form Facades
<div class="col-sm-4">
<form method="POST" action="{{ route('tour-category.update', $category->id) }}">
{{ method_field('PUT') }}
{{ csrf_field() }}
<label for="name">Name</label>
<input type="text" id="name" name="name" class="form-control">
</form>
</div>
use
{{ Form::text('name',null,['class'=>'form-control','id'=>'name']) }}
instead of
<input type="text" class="form-control" id="name" name="name">