Laravel validation with create form: retrieve old input data for dropdown box - laravel

I have a Laravel application which uses a form to create items. The form uses validation as defined in the Laravel documentation under this section.
I have a StoreItem Request file:
public function rules() {
return [
'item_name'=>'required',
'category_id'=> 'required',
'collection_id'=> 'required',
'brewery_id'=> 'required',
];
}
and in the controller I have the following:
public function store(storeItem $request)
{
$validated = $request->validated();
$item = new Item([
'user_id' => Auth::id(),
'item_name' => $request->item_name,
'category_id' => $request->category_id,
'collection_id' => $request->collection_id,
'brewery_id' => $request->brewery_id,
]);
$item->save();
When validation is catching an error, the create form is presented again but I don't see the old input data.
For the input text fields, I have done the following:
<input type="text" class="form-control" name="item_name" value="{{ old('item_name') }}" />
and this shows the old input data, but what to do for the dropdown boxes like category_id, collection_id and brewery_id. I want them to have the old value as the 'selected' value.
Currently in the form I have (for the dropdown boxes):
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}">{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>
This source seems to indicate that using the old() method might even not be needed, but if I don't use the

You need to manually add the selected attribute to the previously selected value. For example:
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}" {{ old("brewery_id") == $brewery->id ? "selected" : "" }}>{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>

try this as well. I've added bracket open and close to (old('brewery_id')==$brewery->id)
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}" {{ (old('brewery_id') == $brewery->id)? "selected" : "" }}>{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>

Related

How to get the old value in a select without unchecked with option formed with an foreach

I need a little help..
In case of validation errors, when the page is reloaded I lose the information entered previously.
This is my code:
Controller:
public function create()
{
$nationalities = array('Italian','Brazilian','Spanish','Romanian');
return view('guest.create', ['nationalities'=>$nationalities);
}
public function store(Request $request)
{
$request->validate([
'nationality' => 'required'
]);
Guest::create([
'nationality' => $request->nationality
]);
return redirect(route('guest.index'));
}
View:
<div class="mb-3">
<label for="nationality" class="form-label fw-bold">Select<span class="required">*</span></label>
<select class="form-select" id="nationality" name="nationality" aria-label="Floating label select example">
#foreach($nationalities as $nationality)
<option value="{{$nationality}}">{{$nationality}}</option>
#endforeach
</select>
</div>
How can I modify the code so that this doesn't happen?
How can you select back what failed if you did not even ask for the old value?
This may or not work depending on how you are validating, but you did not want to show that...
<div class="mb-3">
<label for="nationality" class="form-label fw-bold">Select<span class="required">*</span></label>
<select class="form-select" id="nationality" name="nationality" aria-label="Floating label select example">
#foreach($nationalities as $nationality)
<option value="{{$nationality}}" {{ old('nationality') === $nationality) ? 'selected="selected"' : '' }}>{{$nationality}}</option>
#endforeach
</select>
</div>
<option value="{{$nationality}}" #selected(old('nationality')==$nationality)>
{{$nationality}}
</option>
add the #selected directive in blade.

How can I pre-fill form data entered by a user in Laravel 7

I'm making a registration form where users will be redirected to a preview page to confirm their details first before submitting the form. I'm using Laravel 7 and I'm quite new to Laravel. Once the user enters their details in registration form, the same details will be pre-filled in the preview form before submission. I have tried some code in my controller but it's giving me an error Trying to get property 'myForm' of non-object In my Controller, $data is an array, I'm not sure how I can achieve this. Please help.
In my Conroller:
public function confirmation(Request $request)
{
$categories = Category::all();
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'telephone_number' => 'required|digits:10',
'email' => 'required|string|email|max:255|unique:users','regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
'region' => 'required|string',
'description' => 'required|string|max:2500',
'start_date' => 'required|date',
'client_region' => 'string|max:500',
'client_category' => 'integer|max:255',
]);
$data['myForm'] = $request->all();
return view('auth.client.preview', compact('categories', 'data'));
}
In my blade view:
<div class="form-group">
<label for="first_name">First Name</label><span class="text-danger">*</span>
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data->myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
<div class="invalid-feedback">
{{ $errors->first('first_name') }}
</div>
</div>
My Route:
Route::post('/preview-details', 'Auth\Client\PreviewRegisterDetailsController#confirmation')->name('preview-details');
Dropdown List:
<label for="fundi_type">Fundi Type</label><span class="text-danger">*</span>
<select class="custom-select" id="category_id" name="category_id">
#foreach($categories as $category )
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
Simplify like this below .So no need to create extra array key .
$myForm = $request->all();
return view('auth.client.preview', compact('categories', 'myForm'));
and in view
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
Updated
<option value="{{ $category->id }}" {{($myForm['category_id']==$category->id)?'selected':null}}>{{ $category->name }}</option>
Edit your blade file code.
Actually your controller is sending array and you are accessing that array as a collection.
From :
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data->myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
To
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data['myForm']['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
Hope this will be useful.

No error with Fail Save and show 302 post error... How To solve it?

<div class="row">
<div class="col-md-6">
<h3>Create New Expenses</h3>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form" method="POST" action="{{ route('exp.store') }}" autocomplete="off">
<div class="form-group">
<label>Seller :</label>
<input type="text" name="seller_name" class="form-control" value="{{ old('seller_name',isset($exp) ? $exp->seller_name : '') }}" placeholder="Seller">
</div>
<div class="form-group">
<label>Date :</label>
<input type="date" name="date" class="form-control" value="{{ old('date',isset($exp) ? $exp->date : '') }}">
</div>
<div class="form-group">
<label>Select Type :</label>
<select class="form-control" name="category" value="">
<option value=""> Select Type </option>
<option value="1"{{ isset($exp) ? ($exp->category == 1 ? 'selected' : '') : '' }}> Communication </option>
<option value="2"{{ isset($exp) ? ($exp->category == 2 ? 'selected' : '') : '' }}> Transport </option>
<option value="3"{{ isset($exp) ? ($exp->category == 3 ? 'selected' : '') : '' }}> Tools </option>
<option value="4"{{ isset($exp) ? ($exp->category == 4 ? 'selected' : '') : '' }}> Raw Material </option>
</select>
</div>
<div class="form-group">
<label>Amount(RM) :</label>
<input type="number" name="amount" class="form-control" value="{{ old('amount',isset($exp) ? $exp->amount : '') }}" placeholder="0.00">
</div>
<br>
<button type="submit" class="btn btn-primary btn-sm">Save</button>
<a class="btn btn-danger btn-sm" href="{{ route('exp.index') }}">Cancel</a>
</form>
</div>
</div>
This is my saving data function
public function store(Request $request){
$this->validate($request, [
'seller_name' => 'required|max:50',
'date' => 'required',
'category' => 'required',
'amount' => 'required'
]);
DB::beginTransaction();
try{
$exp = new Exp();
$this->saveData($exp, $request);
DB::commit();
return redirect()->route('exp.index');
} catch (\Exception $ex){
DB::rollback();
return back()->withInput()->withErrors('Fail to save.');
}
}
private function saveData($exp, Request $request){
$exp->seller_name = $request->input('seller_name');
$exp->date = $request->input('date');
$exp->category = $request->input('category');
$exp->amount = $request->input('amount');
$exp->save();
}
This is my Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Exp extends Model
{
protected $table = 'exp';
public $primaryKey = 'exp_id';
}
I'm new using this MVC .... i don't know why cant't saving but all my code look no error.
I try to find it but i find nothing ..
I need some help...
i already provide my view, controller and model
and below is my web.php
Route::get('/exp/create', 'ExpController#create')->name('exp.create');
Route::post('/exp/store', 'ExpController#store')->name('exp.store');
TQ.
Seems like you forgot to add mass assignment fields to your Exp model, hence the fields are not saved in your database. Add all the fields you want to be mass assigned to your model, and it should be working as expected:
protected $fillable = ['field_1', 'field_2', .... 'etc'];
Read more about this on official documentation

how to convert select box html to form html collactive

Hi i have this in my controller
$listPatient = Patient::get();
return view('backend.consultations.create')->with([
'patient' => $this->patient,
'patient_id' =>$this->patient_id,
'listPatient' => $listPatient,
]);
and in my view i have
<div class="form-group">
<div class="col-md-2">
List clients
</div>
<div class="col-lg-10">
<select name="patient_id">
<option value="0">Veillier séléctionner un patien </option>
#foreach($listPatient as $key)
<option value="{{$key->id}}">{{$key->nom_patient}} {{$key->prenom_patient}}</option>
#endforeach
</select>
</div><!--col-lg-10-->
</div><!--form control-->
and it work fine,i want to use Form::select but it doesn't work can anyone help me please
In your controller you would want the following to fetch $listPatient
$listPatient = Patient::lists("nom_patient","id")->toArray();
and in your view you would want
{!! Form::select('patient_id', [0 => 'Veillier séléctionner un patien'] + $listPatient, null) !!}
a simple solution
enter code here : <div class ="form-group">
{{ Form::label('list_patient', trans('validation.attributes.backend.consultations.nom_patient'), ['class' => 'col-lg-2 control-label required']) }}
<div class="col-lg-10">
<select id="patient_id" name="patient_id" class="form-control select2 box-size" required="required" placeholder=" Non définie" >
<option value="">Non définie</option>
#foreach($listPatient as $key)
<option value ="{{$key->id}}">{{$key->nom_patient}} {{$key->prenom_patient}}</option>
#endforeach
</select>
</div><!--col-lg-3-->
</div><!--form control-->

Laravel chosen-select retrieving old value from the form

I am trying to retrieve old value from my form on the edit form, but it seems impossible to find an answer, because everyone in the world decided to use Form::select from laravelcollective/html library. I am trying to use the regular HTML to work this, and it's not able to retrieve old value from the form.
This is my HTML Code.
<div class="col-xs-12 form-group">
<label class="control-label">Role*</label>
<select name="roles[]" data-placeholder="Choose a Role for this User..." class="chosen-select" multiple tabindex="4">
<option value="">Select</option>
#foreach ($roles as $key => $value)
<option value="{{ $key }}" {{ in_array($key, old("roles")) ? "selected":"") }} >{{ $value }}</option>
#endforeach
</select>
</div>
This is my controller code.
public function edit($id)
{
$roles = Role::get()->pluck('name', 'id');
$user = User::findOrFail($id);
return view('admin.users.edit', compact('user', 'roles'));
}
I am trying to convert the following into regular html
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('role', trans('global.users.fields.role').'*', ['class' => 'control-label']) !!}
{!! Form::select('role[]', $roles, old('role') ? old('role') : $user->role->pluck('id')->toArray(), ['class' => 'form-control select2', 'multiple' => 'multiple', 'required' => '']) !!}
<p class="help-block"></p>
#if($errors->has('role'))
<p class="help-block">
{{ $errors->first('role') }}
</p>
#endif
</div>
</div>
Try this:
<div class="col-xs-12 form-group {{ $errors->has('role') ? 'has-error' : '' }}">
<label for="role" class="control-label">Role *</label>
<select class="form-control select2" name="role[]" id="role" required multiple>
#foreach ($roles as $id => $label)
<option value="{{ $id }}" #if (collect(old('role', $user->role->pluck('id') ?? []))->contains($id)) selected="selected" #endif>{{ $label }}</option>
#endforeach
</select>
<span class="help-block">
#if ($errors->has('role'))
{{ $errors->first('role') }}
#endif
</span>
</div>
In your controller's update/store function, make sure you either use the built-in validation methods, which will populate the session on any errors.
or
If you have other checks, make sure you return the input when redirecting back.
return redirect()->back()
->withInput() // <- return input with redirect, will populate session
->with('error', 'Persist failed'); // <- optional

Resources