Form validation in select field - php

Is there a way I can check if a user didn't manipulate the form? In my form, I get all available entries, but if a user changes the value id in the browser, I would just get an error. Any tips:)?
<div class="form-group-row club col-lg-10">
<label>Choose Product</label>
<select name="product_id" class="form-control" required>
#foreach($products as $product)
<option value="{{$product->id}}">{{$product-> product}}</option>
#endforeach
</select>
</div>

You could use a Rule to validate the received data like :
use Illuminate\Validation\Rule;
Validator::make($data, [
'product_id' => [
'required',
Rule::in([/*array of products ids here*/]),
],
]);
Take a look at https://laravel.com/docs/5.8/validation#rule-in
You could use exists like :
Validator::make($data, [
'product_id' => [
'required',
'exists:table_name,column_name'
],
]);

you can do select readonly
<select name="product_id" class="form-control" required readonly>
but user can change html by devtools
also you can check it on backend side like this
if ($products->pluck('id')->diff(request()->input('product_id'))->empty()) {
//not changed
}

Related

How to validate array field value in laravel

I have created the form and created multiple fields.
<input name="members[]" type="text" class="form-control">
<input name="members[]" type="text" class="form-control">
<input name="members[]" type="text" class="form-control">
set the validation from the Form Request for the input fields
public function rules()
{
return [
'password' => 'required|max:30',
'members.*' => 'required|max:12',
];
}
How can we check the members' field value exists in the database using the validation?
For password using like this
'password' => ['required', function ($attribute, $value, $fail) {
if (!\Hash::check($value, $this->user()->password)) {
$fail('Old Password did not match to our records.');
}
}],
You want to use the exists validation rule.
Just extend your existing validation rules for members:
'members.*' => 'required|max:12|exists:{phone number table},{phone nummber column}',

Laravel - multiple selection and saving to database

I have this small project for car posts. I make my post so everything is working properly, but now i need to have multiple selections. So this is my PostsController:
...
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'brand' => 'required',
'model' => 'required',
'age' => 'required',
'cc' => 'required',
'hp' => 'required',
'body' => 'required',
'fuel' => 'required',
'safety' => 'required'
]);
$post = new Post;
$post->title = $request->input('title');
$post->brand = $request->input('brand');
$post->model = $request->input('model');
$post->age = $request->input('age');
$post->cc = $request->input('cc');
$post->hp = $request->input('hp');
$post->body = $request->input('body');
$post->fuel = $request->input('fuel');
$post->safety = $request->input('safety');
$post->save();
return redirect('/home')->with('success', 'Your post is posted!');
}
...
And now this is my createpost.blade.php :
...
<div class="column">
<label for="safety">Safety:</label></br>
<select class="form-control" name="safety">
<option value="" disabled selected>Select your option</option>
<option value="diesel">ABS</option>
<option value="gasoline">ESP</option>
<option value="electric">CHILD LOCK</option>
<option value="electric">AirBAG</option>
</select>
</div>
...
How can i make this select input for multiple selection and all of the selections need to save into my database? I have my Post.php model:
...
class Post extends Model
{
protected $table = 'posts';
protected $primaryKey = 'id';
}
Please help if anybody have solutions for this? Or some tutorials or any help similar!
Try some multi select libraries
Select2 is one among them
Use array in your blade.php file and also use multiple
<select class="form-control" name="safety[]" multiple>
In controller
$post->safety = implode(',', $request->input('safety'));
You can use checkbox in blade file
$("input:checkbox").click(function(e){
console.log(e.target.checked ? e.target.value : e.target.value+' is unchecked')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label for="safety">Safety:</label></br>
<input type="checkbox" value="ABS" name="safety[]" />ABS
<input type="checkbox" value="ESP" name="safety[]" />ESP
<input type="checkbox" value="CHILD LOCK" name="safety[]" />CHILD LOCK
<input type="checkbox" value="AirBAG" name="safety[]" />AirBAG
</div>
And retrieve your data from $request in controller as follows:
$request->input('safety') // return an array with all checked value, e.g: ['ABS','ESP']
add multiple attribute in select tag
change
<select class="form-control" name="safety[]">
to
<select class="form-control" name="safety[]" multiple>
This will let you select multiple options.
User will have to use control/cmd key to select multiple options

Laravel - prepopulate input data after validation failed

I used 5.4 and I've an index action in convert controller which shows the form and then have another action calculate in the convert controller. So the form has from-currency, amount, to-currency input and all of them are required.
Here's the validation I've for calculate action:
$this->validate(request(), [
'from_currency' => 'required|min:3|max:3|alpha',
'to_currency' => 'required|min:3|max:3|alpha',
'amount' => 'required|numeric',
]);
If the validation failed I want when showing the errors and the form it will prepopulate the input already.
Is there like a function I can use for Request ? I know how to get the domain/path inside blade like Request::root() and I also tried Request::input('from_currency) in the view but not work.
I even tried to set the view data like 'from_currency' => request('from_currency') and it's blank. Any idea?
When you are validating your form your request if it fail you can redirect to the same page with all the input which was submited
$validator = Validator::make($request->all(), [
'from_currency' => 'required|min:3|max:3|alpha',
'to_currency' => 'required|min:3|max:3|alpha',
'amount' => 'required|numeric',
]);
if ($validator->fails()) {
return redirect('index')
->withErrors($validator)
->withInput();
}
and in your blade view you can show the old value by ussing the old helper like this
<input type="text" name="from_currency" value="{{ old('from_currency') }}">
<input type="text" name="to_currency" value="{{ old('to_currency') }}">
<input type="text" name="amount" value="{{ old('amount') }}">
Try this
In your blade file, make sure your inputs have this:
<input type="text" ... value="{{ old('from_currency') }}" ... >.
Then in your controller...
if($validation->fails()) {
return redirect()->back()->withInput();
}
You can also user Validate instead of Validator::make.
eg
$this->validate($request, [
'question' => "required|min:10|max:100",
'answer' => "required|min:20|max:300",
'rank' => "required|numeric|gt:0|lt:100",
]);
Then in your form use
<input type="text" class="form-control" id="question" name="question" value="{{ old('question') }}">
This will automatically redirect back with input if the validator fails.
This way, you DO NOT have to include
if($validation->fails()) {
return redirect()->back()->withInput();
}

multiple select field - select field must be an array and just one <option> is shown in the $request output

I have the code below that is a resume of the process to create a new conference. To create a new conference is ncessary that the user introduce some info like the conference name, etc. The user also needs to introduce between 1 and 3 categories for the conference.
So there is a select element using select2 plugin so the user can select the categories:
<div class="form-row">
<div class="form-group col-lg-6">
<label for="categories">Category</label>
<select id="tag_list" required multiple class="form-control" value="{{ old('categories') }}" name="categories" id="categories">
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
</div>
</div>
Then the laravel code to store the conference info and also the categories of the conference in the conference_category table since there is a many to many relationship between confernece and category:
public function store(Request $request)
{
$this->validate($request, [
'conference_name' => 'required|max:255|string',
'conference_categories' => 'required|array|between:1,3|integer',
]);
$conference = Conference::create([
'name' => $request->conference_name,
]);
$conference->categories()->attach($request->conference_categories);
}
The select2 JS:
$(function() {
$('#tag_list').select2({
placeholder: '',
dropdownAutoWidth: 'true',
width: '100%'
});
});
Errors
If the user selects more than one category in the $request output just appears the id of one category
And it appears a laravel validation error after submit the form "The conference categories must be an array.
"
Do you know where can be the issue?
You gotta change the name attribute of your select to an array, like this and also remove one id attribute from it, it can't have 2
<select required multiple class="form-control" value="{{ old('categories') }}" name="categories[]" id="categories">

Laravel 5.1 registration form with new field

I am creating referral system so I have the following routes
// Registration routes...
Route::get('auth/register/{id}', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
and my RegisterUser.php is changed to
public function getRegister($id)
{
return view('auth.register')->withName($id);
}
and my blade looks like
<div class="form-group">
<label class="col-md-4 control-label">Company</label>
<div class="col-md-6">
<input type="text" class="form-control" name="company" value="{{ old('company') }}" readonly disabled>
</div>
</div>
in AuthController I have:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'company' => $data['company'],
'password' => bcrypt($data['password']),
]);
}
and the value="{{ old('company') }}" is causing the problem. When it is like that it works. But I want the value to be value="{{$name}}" given from return view('auth.register')->withName($id); So when I go to route auth/register/something in the input field I have got the 'something' so it is working but I have the error code "Undefined index: company". When I remove the value at all it is working but I need this value. Any suggestions would be helpful.
The Problem of your code is the disabled attribute in the input "company", why ? well a disabled element isn't editable and isn't sent on submit. so Laravel doesn't receive it so you will be able to access via the helpers old.
Remove the disabled attribute and the magic happens.
<input type="text" class="form-control" name="company" value="{{ old('company') }}" readonly >

Categories