Validation in dynamic form Laravel 5.5 - php

How can I create a validtion for a dynamic form?
//Controller
public function store(Request $request)
{
$rules = [
'companyName' => 'required',
'bannerName' => 'required',
'bannerDescription' => 'required',
'bannerURL' => 'required',
'bannerImg' => 'required',
];
$customMessages = [
'companyName.required' => 'Yo, what should I call you?',
'bannerName.required' => 'Yo, what should I call you?',
'bannerDescription.required' => 'Yo, what should I call you?',
'bannerURL.required' => 'Yo, what should I call you?',
'bannerImg.required' => 'Yo, what should I call you?',
];
$this->validate($request, $rules, $customMessages);
}
And here is my view, my "name" attr are arrays cause I'll store a bulk of data to DB. Clicking on "+ Add Banner" jquery will clone div with the same 4 inputs.
If I'll remove arrays everything will work ofc, but if no I'll get the following error
htmlspecialchars() expects parameter 1 to be string, array given
{!! Form::open(['action' => 'CompanyController#store', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
<div class="form-group{{ $errors->has('companyName') ? ' has-error' : '' }}">
<label for="companyName">Company URL Address</label>
<input type="text" class="form-control" value="{{old('companyName')}}" id="companyName" name="companyName" placeholder="example.com">
<small class="text-danger">{{ $errors->first('companyName') }}</small>
</div>
<hr>
<div data-sel-baner-box>
<div data-sel-baner-form>
<div class="panel-heading"><h4 style="text-align: center">New banner</h4></div>
<div class="form-group{{ $errors->has('bannerName') ? ' has-error' : '' }}">
<label for="bannerName">Title</label>
<input type="text" class="form-control" id="bannerName" value="{{old('bannerName')}}" name="bannerName[]" placeholder="Name">
<small class="text-danger">{{ $errors->first('bannerName') }}</small>
</div>
<div class="form-group{{ $errors->has('bannerDescription') ? ' has-error' : '' }}">
<label for="bannerDescription">Banner Description</label>
<input type="text" class="form-control" id="bannerDescription" value="{{old('bannerDescription')}}" name="bannerDescription[]" placeholder="Description">
<small class="text-danger">{{ $errors->first('bannerDescription') }}</small>
</div>
<div class="form-group{{ $errors->has('bannerURL') ? ' has-error' : '' }}">
<label for="bannerURL">Banner URL</label>
<input type="text" class="form-control" id="bannerURL" value="{{old('bannerURL')}}" name="bannerURL[]" placeholder="URL">
<small class="text-danger">{{ $errors->first('bannerURL') }}</small>
</div>
<div class="form-group{{ $errors->has('bannerImg') ? ' has-error' : '' }}">
<label for="bannerImg">File input</label>
<input type="file" class="form-control-file" id="bannerImg" name="bannerImg[]">
<small class="text-danger">{{ $errors->first('bannerImg') }}</small>
</div>
</div>
+ Add Banner
<button type="submit" class="btn btn-primary">Save Company</button>
{!! Form::close() !!}
Any hints please?

You have to use dot notation for array input validation rules as:
$rules = [
'companyName.*' => 'required',
'bannerName.*' => 'required',
'bannerDescription.*' => 'required',
'bannerURL.*' => 'required',
'bannerImg.*' => 'required',
];
You can see docs here.

Related

Laravel 302 when i do a validation

When I do post form in laravel and then validate it from the controller I get this response :
302 found
nothing useful, I`ve tried everything but nothing worked with me.
My Form blade :
<form action="{{route('newitem')}}" method="post">
#csrf
<div class="mb-3">
<label for="item name" class="form-label">Email address</label>
<input type="text" class="form-control" id="item name" name="item_name" >
</div>
<div class="mb-3">
<label for="price" class="form-label">Price</label>
<input type="number" class="form-control" id="price" name="item_price">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
my controller :
public function new_item(Request $rq){
$validated = $rq->validate(
[
'item_name' => 'required|string|min:4|max:90',
'item_desc' => 'string|min:4|max:90',
'item_price' => 'required|integer|min:4'
]
);
UsrsItem::create([
'item_name' => $validated->item_title,
'item_price' => $validated->item_price,
]);
}
I hope someone can help me with that :<
Contrroller Code
public function new_item(Request $rq){
$validated = $rq->validate(
[
'item_name' => 'required|string|min:4|max:90',
'item_desc' => 'string|min:4|max:90',
'item_price' => 'required|integer|min:4'
]
);
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
UsrsItem::create([
'item_name' => $validated->item_title,
'item_price' => $validated->item_price,
]);
return response()->json(['success'=>'Record is successfully added']);
}
Put This In Blade File
#if ($errors->has())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</div>
#endif

How to get saved value from dropdown in edit page laravel?

inside EmployeeController in the edit function, i have this code
public function edit($id)
{
$employees = Employee::find($id);
$departmentlists = Department::pluck('id', 'name');
return view('employees.edit', compact('employees', 'departmentlists'));
}
and inside edit.blade.php to display the dropdown i have this code
{!! Form::open(['action' => ['EmployeeController#update', $employees->id], 'method' => 'POST', 'autocomplete' => 'off', 'class' => 'form-horizontal', 'enctype' => 'application/x-www-form-urlencoded']) !!}
<div class="card">
<div class="card-header card-header-primary">
<h4 {{ Form::label('', 'Change Employee Data', ['class' => 'card-title']) }}
</h4>
<p class="card-category"></p>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12 text-right">
<a href="{{ route('employees.index') }}" class="btn btn-sm btn-primary" style="font-size:12px">
<i class="material-icons">keyboard_backspace</i>
{{ __('kembali') }}
</a>
</div>
</div>
<div class="row">
{{ Form::label('Name', '', ['class' => 'col-sm-2 col-form-label']) }}
<div class="form-group col-sm-7">
{{Form::text('name', $employees->name, ['class' => 'form-control', 'placeholder' => 'Name', 'required'])}}
<p style="color: red;">#error('name') {{ $message }} #enderror</p>
</div>
</div>
<div class="row">
{{ Form::label('Department', '', ['class' => 'col-sm-2 col-form-label']) }}
<div class="col-md-7">
<div class="form=group">
#foreach($departmentlists as $dl)
<option value="{{ $dl->id }}" #if($dl->id==$employees->department_id) selected='selected' #endif >{{ $employees->name }}</option>
#endforeach
<p style="color: red;">#error('id') {{ $message }} #enderror</p>
</div>
</div>
</div>
<div class="row">
{{ Form::label('Keterangan', '', ['class' => 'col-sm-2 col-form-label']) }}
<div class="form-group col-sm-7">
{{ Form::textarea('information', $employees->information, ['class' => 'form-control', 'placeholder' => 'Keterangan', 'rows' => '6', 'cols' => '50']) }}
</div>
</div>
</div>
<div class="card-footer ml-auto mr-auto">
{{ Form::hidden('_method','PUT') }}
{{ Form::submit('Ubah', ['class' => 'btn btn-primary']) }}
</div>
</div>
{!! Form::close() !!}
This is the employees table
and this is departments table
Now, the goal is i want the dropdown on edit page to display department name of the employee belongs to, while the dropdown still have all of the department name.
so i change can it, but when i run this code it gives me this error.
Trying to get property 'id' of non-object (View:
C:\xampp\htdocs\ims-it-laravel7\resources\views\employees\edit.blade.php)
i have read other threads here but those code still doesn't solve the problem
$departmentlists = Department::pluck('id', 'name');
Later You use
#foreach($departmentlists as $dl) and $dl->id
$dl is NOT an object, it is an array because of the pluck() function.
More precisely it looks like this
[
"abc" => 1
"xyz" => 2
"foo" => 3
]
Note: To see it Yourself try using dd($departmentlists) or dump($departmentlists)
Please see Laravel Eloquent Pluck
In this case You might want to use Department::select(['id', 'name'])->get() as it will return collection of objects with specified properties.

The 0 field is required. Laravel 5.5 Validation error

Am having a "The 0 field is required." error while trying save data into database when I have no field called 0. without validation from the Controller, the data saves but if I validate even just one field out of the six field I want to validate, I still get the error. How do I solve the issue. Please help out here is my view
<form method="post" action="{{ url('agent/add_tenantProperty') }}" data-toggle="validator">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtMovieTitle">Tenant</label>
<select id="ddlGenge" class="form-control" name="tenant_id" required="">
#foreach($tenants as $tenant)
<option value="{{ $tenant->id }}">
{{ $tenant->designation }} {{ $tenant->firstname }} {{ $tenant->lastname }}
</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="ddlGenge">Asset Category</label>
<select id="ddlGenge" class="form-control" name="asset_id" required="">
<option>Choose a Property</option>
#foreach($assets as $asset)
<option value="{{ $asset->id }}">{{ $asset->category }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtDirector">Asset description</label>
<select id="ddlGenge" class="form-control" name="description" required="">
<option>Choose a Description</option>
#foreach($assets as $asset)
<option value="{{ $asset->description }}">{{ $asset->description }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="txtProducer">Location</label>
<select id="ddlGenge" class="form-control" name="address" required="">
<option>Choose an Address</option>
#foreach($assets as $asset)
<option value="{{ $asset->address }}">{{ $asset->address }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtWebsite">Standard price</label>
<input id="txtWebsite" type="text" class="form-control" name="price" required="">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="txtWriter">Date</label>
<input id="txtWriter" type="date" class="datepicker form-control" name="occupation_date"
required="">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<button type="submit" class="btn btn-outline btn-primary pull-right">Submit</button>
<br/>
</form>
and my controller
public function store(Request $request)
{
//validation
$this->validate($request, array([
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
]));
//create and save new data
$tenantProperty = New TenantProperty();
$tenantProperty->tenant_id = $request->tenant_id;
$tenantProperty->asset_id = $request->asset_id;
$tenantProperty->description = $request->description;
$tenantProperty->address = $request->address;
$tenantProperty->price = $request->price;
$tenantProperty->occupation_date = $request->occupation_date;
$tenantProperty->save();
//redirect
return redirect('agent/tenantProperty_list');
}
with the route as follows
Route::get('add_tenantProperty', 'TenantPropertyController#create')->name('/add_tenantProperty');
Route::post('add_tenantProperty', 'TenantPropertyController#store');
When you just write $request, it passes the entire request object but the validate function expect both the arguments to be arrays.
So make a little change and you will be good to go:
$this->validate($request, array( // Removed `[]` from the array.
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
));
The above answer is correct, this is another way to solve the validation problem on laravel 5.5 I asked
$validation = validator::make($request->all(), [
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
]);
For more information visit https://laravel.com/docs/5.5/validation#manually-creating-validators
$request->validate([
'0'=>'',
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',]);

Laravel 4 error when changing password

My Controller
public function update($id)
{
if (!is_numeric($id)) {
// #codeCoverageIgnoreStart
return \App::abort(404);
// #codeCoverageIgnoreEnd
}
$temp = Input::all();
$temp['password'] = Hash::make($temp['password']);
//form Processing
$result = $this->userForm->update($temp);
//$result = $this->userForm->update(Input::all());
if ($result['success']) {
// Success!
Session::flash('success', $result['message']);
return Redirect::action('UserController#index', array($id));
} else {
Session::flash('error', $result['message']);
return Redirect::action('UserController#edit', array($id))
->withInput()
->withErrors($this->userForm->errors());
}
}
My View
<div class="form-group {{ ($errors->has('firstName')) ? 'has-error' : '' }}" for="firstName">
{{ Form::label('edit_firstName', 'First Name', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-10">
{{ Form::text('firstName', $user->first_name, array('class' => 'form-control', 'placeholder' => 'First
Name', 'id' => 'edit_firstName'))}}
</div>
{{ ($errors->has('firstName') ? $errors->first('firstName') : '') }}
</div>
<div class="form-group {{ ($errors->has('lastName')) ? 'has-error' : '' }}" for="lastName">
{{ Form::label('edit_lastName', 'Last Name', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-10">
{{ Form::text('lastName', $user->last_name, array('class' => 'form-control', 'placeholder' => 'Last Name',
'id' => 'edit_lastName'))}}
</div>
{{ ($errors->has('lastName') ? $errors->first('lastName') : '') }}
</div>
#if (Sentry::getUser()->hasAccess('admin'))
<div class="form-group">
{{ Form::label('edit_memberships', 'Group Memberships', array('class' => 'col-sm-2 control-label'))}}
<div class="col-sm-10">
#foreach ($allGroups as $group)
<label class="checkbox-inline">
<input type="checkbox" name="groups[{{ $group->id }}]" value='1'
{{ (in_array($group->name, $userGroups) ? 'checked="checked"' : '') }} > {{ $group->name }}
</label>
#endforeach
</div>
</div>
<div class="form-group {{ ($errors->has('password')) ? 'has-error' : '' }}">
{{ Form::password('password', array('class' => 'form-control', 'placeholder' => 'Password')) }}
{{ ($errors->has('password') ? $errors->first('password') : '') }}
</div>
#endif
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
{{ Form::hidden('id', $user->id) }}
{{ Form::submit('Submit Changes', array('class' => 'btn btn-primary'))}}
</div>
</div>
{{ Form::close()}}</div>
I'm trying to update data profile like; first name, last name, member and password.
I cannot update this password, my encryption password like:
$2y$10$mjkd5MRgUEn2JSK52xrrQ.bpDz5WZwAaHje6gd0TbmH7h4H3.7BBO

How to validate checkboxes with Laravel?

I am trying to validate a form in Laravel 5.3. The form has checkboxes. I need at least one checkbox to be selected for the form to be vald. This is my form
Here is my form
<div class="form-group {{ $errors->has('gender') ? 'has-error' : ''}}">
<div class="col-md-2"></div>
<div class="col-md-10">
<label for="gender_" class="checkbox-inline">
{!! Form::checkbox('gender', '', null, ['id' => 'gender_']) !!}
{{ trans('blogs.gender_') }}
</label>
<label for="gender_1" class="checkbox-inline">
{!! Form::checkbox('gender', '1', null, ['id' => 'gender_1']) !!}
{{ trans('blogs.gender_1') }}
</label>
<label for="gender_2" class="checkbox-inline">
{!! Form::checkbox('gender', '2', null, ['id' => 'gender_2']) !!}
Female
</label>
{!! $errors->first('gender', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('name') ? 'has-error' : ''}}">
{!! Form::label('name',trans('blogs.name'),['class' => 'col-md-2 control-label']) !!}
<div class="col-md-10">
{!! Form::text('name',null, ['class' => 'form-control']) !!}
{!! $errors->first('name', '<p class="help-block">:message</p>') !!}
</div>
</div>
I am using FormRequest object. Here is my rules() method
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gender' => 'required'
];
}
However, the validation fails unless I select every checkbox!
How can I correctly ensure that the validation only fails if no checkboxes is selected?
Your rules() looks correct so no require change for it. Try below:
<div class="form-group {{ $errors->has('gender') ? 'has-error' : ''}}">
<div class="col-md-2"></div>
<div class="col-md-10">
<label for="gender_0" class="checkbox-inline">
{!! Form::checkbox('gender[]', 0, null, ['id' => 'gender_0']) !!}
{{ trans('blogs.gender_') }}
</label>
<label for="gender_1" class="checkbox-inline">
{!! Form::checkbox('gender[]', 1, null, ['id' => 'gender_1']) !!}
{{ trans('blogs.gender_1') }}
</label>
<label for="gender_2" class="checkbox-inline">
{!! Form::checkbox('gender[]', 2, null, ['id' => 'gender_2']) !!}
Female
</label>
{!! $errors->first('gender', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('name') ? 'has-error' : ''}}">
{!! Form::label('name',trans('blogs.name'),['class' => 'col-md-2 control-label']) !!}
<div class="col-md-10">
{!! Form::text('name',null, ['class' => 'form-control']) !!}
{!! $errors->first('name', '<p class="help-block">:message</p>') !!}
</div>
</div>
Hope this could help you!

Categories