Laravel exists validation if the given value is not zero - laravel

This is my situation:
Assume I have a radio input in my html form which it's value must to exists in a table only IF user check one of them, else the value have to be zero
this my structure:
<div class="inputGroup">
<input id="first_change1" name="first_change" type="radio" value="{{ $game->teamOne->id }}" {{ old('first_change') == $game->teamOne->id ? 'checked="checked"' : '' }} />
<label for="first_change1" class="farsi">{{ $game->teamOne->name }}</label>
</div>
<div class="inputGroup">
<input id="first_change2" name="first_change" type="radio" value="{{ $game->teamTwo->id }}" {{ old('first_change') == $game->teamTwo->id ? 'checked="checked"' : '' }} />
<label for="first_change2" class="farsi">{{ $game->teamTwo->name }}</label>
</div>
<div class="inputGroup">
<input id="first_change3" name="first_change" type="radio" value="0" {{ old('first_change') == "0" ? 'checked="checked"' : '' }} />
<label for="first_change3" class="farsi">None of them</label>
</div>
#if( $errors->has('first_change'))
<h6 class="alert alert-danger farsi text-danger rtl text-right">
{{ $errors->first('first_change') }} <i class="fa fa-2x fa-arrow-up fleft" style="bottom: 5px !important;"></i>
</h6>
#endif
And this is my current validation for this field:
'first_change' => 'required|exists:fc_teams,id',
But I need something like this:
'first_change' => 'required|[IF VALUE IS NOT -0-; THEN]exists:fc_teams,id',

You could build your validation conditionally:
$first_change_validation = [
'required',
];
if ($request->get('first_change') == 0) {
$first_change_validation[] = 'exists:fc_teams,id';
}
And then use this array in your validation:
$this->validate($request, [
'first_change' => $first_change_validation,
]);

Related

I get "SQLSTATE[23000]: Integrity constraint violation" when I try to add a command

When I try to get a product and command it I get "Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (SQL: insert into commande (name, familyname, quantity, mobile, ville, adresse, id_product, user_id, updated_at, created_at) values (?, ?, ?, ?, ?, ?, ?, ?, 2022-11-21 21:30:27, 2022-11-21 21:30:27))"
I am trying here to command a product where every product has a different user. I am using a foreign key in products table (user_id) and every command has a user to inspect it.
This is my function in the controller:
public function getProduct($id, Request $request)
{
$product = Product::find($id);
$commande = new AppCommande;
$commande->name = $request->input('name');
$commande->familyname = $request->input('familyname');
$commande->quantity = $request->input('quantity');
$commande->mobile = $request->input('mobile');
$commande->ville = $request->input('ville');
$commande->adresse = $request->input('adresse');
$commande->id_product = $request->input('id_product');
$commande->user_id = $request->input('id_user');
$commande->save();
return view('product', ['product' => $product], ['commande' => $commande]);
}
This is my route :
Route::get('/product/{id}', \[ 'uses' =\> 'CommandeUserController#getProduct', 'as' =\> 'product.single' \]);
and this is the view:
#extends('layouts.app')
#section('content')
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="{{ asset('uploads/product/'.$product->image) }}" width="90px" alt="image">
<div class="caption">
<h3> {{$product->name}} </h3>
<p class="discription"> {{$product->description}} </p>
<div class="clearfix">
<div class="pull-left price"/>$ {{$product->price}}</div>
{{-- Commander ce produit --}}
</div>
</div>
</div>
<div class="card">
<div class="card-header">
Create Commande
</div>
<div class="card-body">
<form action="{{ route("admin.commandes.store") }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" value="{{ old('name', isset($commande) ? $commande->name : '') }}">
#if($errors->has('name'))
<em class="invalid-feedback">
{{ $errors->first('name') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.name_helper') }}
</p>
</div>
<div class="form-group {{ $errors->has('familyname') ? 'has-error' : '' }}">
<label for="name">Family Name</label>
<input type="text" id="familyname" name="familyname" class="form-control" value="{{ old('familyname', isset($commande) ? $commande->familyname : '') }}">
#if($errors->has('name'))
<em class="invalid-feedback">
{{ $errors->first('name') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.name_helper') }}
</p>
</div>
<div class="form-group {{ $errors->has('mobile') ? 'has-error' : '' }}">
<label for="quantity">Mobile</label>
<input type="number" id="mobile" name="mobile" class="form-control" value="{{ old('mobile', isset($commande) ? $commande->mobile : '') }}" step="1">
#if($errors->has('mobile'))
<em class="invalid-feedback">
{{ $errors->first('mobile') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.price_helper') }}
</p>
</div>
<div class="form-group {{ $errors->has('quantity') ? 'has-error' : '' }}">
<label for="quantity">Quantity</label>
<input type="number" id="quantity" name="quantity" class="form-control" value="{{ old('quantity', isset($commande) ? $commande->quantity : '') }}" step="1">
#if($errors->has('price'))
<em class="invalid-feedback">
{{ $errors->first('price') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.price_helper') }}
</p>
</div>
<div class="form-group {{ $errors->has('ville') ? 'has-error' : '' }}">
<label for="ville">City</label>
<input type="text" id="ville" name="ville" class="form-control" value="{{ old('ville', isset($commande) ? $commande->familyname : '') }}">
#if($errors->has('ville'))
<em class="invalid-feedback">
{{ $errors->first('ville') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.name_helper') }}
</p>
</div>
<div class="form-group {{ $errors->has('adresse') ? 'has-error' : '' }}">
<label for="adress">Adresse</label>
<input type="text" id="adresse" name="adresse" class="form-control" value="{{ old('adresse', isset($commande) ? $commande->adresse : '') }}">
#if($errors->has('adresse'))
<em class="invalid-feedback">
{{ $errors->first('adresse') }}
</em>
#endif
<p class="helper-block">
{{ trans('global.product.fields.name_helper') }}
</p>
</div>
<input type="hidden" name="id_product" value=" {{ $product->id }}" />
<input type="hidden" name="user_id" value=" {{ $product->user_id }}" />
<input class="btn btn-danger" type="submit" value="{{ trans('global.save') }}">
</div>
</form>
</div>
</div>
#endsection
Hello I changed the getProduct() to and it works:
public function getProduct($id, Request $request)
{
$product = Product::find($id);
return view('product', ['product' => $product]);
}
and I used in the form a new store funtion for the command:
public function store(StoreProductRequest $request)
{
$user_id=auth()->user()->id;
$commande = new AppCommande();
$commande->name = $request->input('name');
$commande->familyname = $request->input('familyname');
$commande->quantity = $request->input('quantity');
$commande->mobile = $request->input('mobile');
$commande->ville = $request->input('ville');
$commande->adresse = $request->input('adresse');
$commande->id_product = $request->input('id_product');
$commande->user_id=$user_id;
$commande->save();
return redirect('/commandeuser/confirm')->with('status', 'commande ajoutée!');
}
Since I feel weird that your error message doesn't take any value from your request, try to add your $commande variable to a standard bracket '()' to your last model initiation.
$commande = new AppComande();

How to return validated value of ID in Laravel validation

So I have created looped generated radio-buttons:
<div class="custom-control custom-radio guest-form">
#foreach(config('const.res_site') as $id => $res)
<div class="form-radio">
<input class="custom-control-input" type="radio" onchange="otherResSite({{$id}})" id="{{$res}}" value="{{$id}}"
name="reservation_site" {{ old("reservation_site") == $id ? "checked" : "" }}>
<label for="{{ $res }}" class="custom-control-label">{{ $res }}</label>
</div>
#endforeach
<div class="otherField" id="ifOtherSite" class="otherSite" style="display: {{ old('reservation_site') == 4 ? 'display:inline-flex' : 'none' }}">
<input type='text' class="form-control" id='otherSite' name='otherSite' value="{{ old('otherSite', '') }}"><br>
</div>
</div>
#if ($errors->has('otherSite'))
<div class="form-group">
<p class="text-danger">{{ $errors->first('otherSite') }}</p>
</div>
#endif
const.php
'res_site' => [
0 => 'site1',
1 => 'site2',
2 => 'other',
],
This one is to validate the otherSite value if selected option is other. It now works well but the validation message returned is like this:
The other site field is required when reservation site is 2.
My validator is like this:
return [
'reservation_site' => ['required'],
'otherSite' => ['required_if:reservation_site,2'],
]
Now, how can I make its return message as
The other site field is required when reservation site is other
Is there any way I can do that?
Okay. If someone might need this someday, I did it this way:
<input class="custom-control-input" type="radio" id="{{$res}}" value='{{$id == 4 ? "other" : $id}}'>
and in my validation:
return [
'reservation_site' => ['required'],
'otherSite' => ['required_if:reservation_site,other'],
]

Save options radios or checkbox

I want to save radio from form in database but I get "on" in the database, I don't know why.
I tried to use HTML form with labels, radios and checkbox but I see in the database saving "on".
Controller :
public function store(Request $request, Survey $survey)
{
// remove the token
$arr = $request->except('_token');
foreach ($arr as $key => $value) {
$newAnswer = new Answer();
if (! is_array( $value )) {
$newValue = $value['answer'];
} else {
$newValue = json_encode($value['answer']);
}
$newAnswer->answer = $newValue;
$newAnswer->question_id = $key;
$newAnswer->user_id = Auth::id();
$newAnswer->survey_id = $survey->id;
$newAnswer->save();
$answerArray[] = $newAnswer;
};
return redirect()->action('SurveyController#view_survey_answers', [$survey->id]);
}
view :
{!! Form::open(array('action'=>array('AnswerController#store', $survey->id))) !!}
#forelse ($survey->questions as $key=>$question)
<p class="flow-text">Question {{ $key+1 }} - {{ $question->title }}</p>
#if($question->question_type === 'text')
<div class="input-field col s12">
<input id="answer" type="text" name="{{ $question->id }}[answer]">
<label for="answer">Answer</label>
</div>
#elseif($question->question_type === 'textarea')
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" name="{{ $question->id }}[answer]"></textarea>
<label for="textarea1">Textarea</label>
</div>
#elseif($question->question_type === 'radio')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input name="{{ $question->id }}[answer]" type="radio" id="{{ $key }}" />
<label for="{{ $key }}">{{ $value }}</label>
</p>
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input type="checkbox" id="something{{ $key }}" name="{{ $question->id }}[answer]" />
<label for="something{{$key}}">{{ $value }}</label>
</p>
#endforeach
#endif
<div class="divider" style="margin:10px 10px;"></div>
#empty
<span class='flow-text center-align'>Nothing to show</span>
#endforelse
{{ Form::submit('Submit Survey', array('class'=>'btn waves-effect waves-light')) }}
{!! Form::close() !!}
You forgot to give a value attribute to your checkbox and radio inputs, for example something like this:
<input name="{{ $question->id }}[answer]" type="radio" id="{{ $key }}" value="{{ $key}}"/>
<input type="checkbox" id="something{{ $key }}" name="{{ $question->id }}[answer]" value="{{ $key}}"/>

Custom validation rules required when select box

I have a scope that can select company, store, department, when selecting company, the company field will appear for users to enter. similarly when selecting the store, the company and store fields will appear for users to enter. and when selecting the department, all 3 fields appear. My problem is that I have to set the rule so that when selecting company, only company will be requried, when the store is selected, the company and store fields are requried. Here are the rules, but all 3 fields are required. Click on scope and show the corresponding fields, I write in the script
This is the rules function:
public function rules()
{
return [
'assigned_company' => 'required',
'assigned_store' =>'required',
'assigned_department' =>'required',
];
}
public function messages()
{
return [
'assigned_company.required' => 'The company field is required.',
'assigned_store.required' => 'The store field is required.',
'assigned_department.required' => 'The department field is required.'
];
}
And script:
$('input[name=checkout_to_type_contract]').on("change",function () {
var object_type = $('input[name=checkout_to_type_contract]:checked').val();
var object_id = $('#assigned_company option:selected').val();
if (object_type == 'company') {
$('#current_assets_box').fadeOut();
$('#assigned_company').show();
$('#assigned_store').hide();
$('#assigned_department').hide();
$('.notification-callout').fadeOut();
} else if (object_type == 'store') {
$('#current_assets_box').fadeOut();
$('#assigned_company').show();
$('#assigned_store').show();
$('#assigned_department').hide();
$('.notification-callout').fadeOut();
} else {
$('#assigned_company').show();
$('#assigned_store').show();
$('#assigned_department').show();
if (object_id) {
$('#current_assets_box').fadeIn();
}
$('.notification-callout').fadeIn();
}
});
This is html. because it is too long so i will take the related parts
<!--Scope-->
<div class="form-group" id="assignto_selector"{!! (isset($style)) ? ' style="'.e($style).'"' : '' !!}>
{{ Form::label('name', trans('general.scope'), array('class' => 'col-md-3 control-label')) }}
<div class="col-md-8">
<div class="btn-group" data-toggle="buttons">
#if ((isset($scope_company_contract)) && ($scope_company_contract!='false'))
<label class="btn btn-default active">
<input name="checkout_to_type_contract" value="company" type="radio" checked="checked"><i class="fa fa-user"></i> {{ trans('general.company') }}
</label>
#endif
#if ((isset($scope_store_contract)) && ($scope_store_contract!='false'))
<label class="btn btn-default">
<input name="checkout_to_type_contract" value="store" type="radio"><i class="fa fa-barcode"></i> {{ trans('general.store') }}
</label>
#endif
#if ((isset($scope_department_contract)) && ($scope_department_contract!='false'))
<label class="btn btn-default">
<input name="checkout_to_type_contract" value="department" class="active" type="radio"><i class="fa fa-map-marker"></i> {{ trans('general.department') }}
</label>
#endif
{!! $errors->first('checkout_to_type_contract', '<span class="alert-msg"><i class="fa fa-times"></i> :message</span>') !!}
</div>
</div>
</div>
<!-- Company -->
<div id="assigned_company" class="form-group{{ $errors->has($fieldname) ? ' has-error' : '' }}"{!! (isset($style)) ? ' style="'.e($style).'"' : '' !!}>
{{ Form::label($fieldname, $translated_name, array('class' => 'col-md-3 control-label')) }}
<div class="col-md-7{{ ((isset($required) && ($required =='true'))) ? ' required' : '' }}">
<select class="js-data-ajax" data-endpoint="companies" data-placeholder="{{ trans('general.select_company') }}" name="{{ $fieldname }}" style="width: 100%" id="company_select">
#if ($company_id = Input::old($fieldname, (isset($item)) ? $item->{$fieldname} : ''))
<option value="{{ $company_id }}" selected="selected">
{{ (\App\Models\Company::find($company_id)) ? \App\Models\Company::find($company_id)->name : '' }}
</option>
#else
<option value="">{{ trans('general.select_company') }}</option>
#endif
</select>
</div>
{!! $errors->first($fieldname, '<div class="col-md-8 col-md-offset-3"><span class="alert-msg"><i class="fa fa-times"></i> :message</span></div>') !!}
</div>
<!-- Store -->
<div id="assigned_store" class="form-group{{ $errors->has($fieldname) ? ' has-error' : '' }}"{!! (isset($style)) ? ' style="'.e($style).'"' : '' !!}>
{{ Form::label($fieldname, $translated_name, array('class' => 'col-md-3 control-label')) }}
<div class="col-md-7{{ ((isset($required) && ($required =='true'))) ? ' required' : '' }}">
<select class="store_select" data-endpoint="" data-placeholder="Select Store" name="{{ $fieldname }}" style="width: 100%" id="store_select">
#if ($storeSelect = Input::old($fieldname, (isset($item)) ? $item->{$fieldname} : ''))
<option value="{{ $storeSelect }}" selected="selected">
{{ (\App\Models\Store::find($storeSelect)) ? \App\Models\Store::find($storeSelect)->name : '' }}
</option>
#else
<option value="">{{ trans('admin.store.table.select_store') }}</option>
#endif
</select>
</div>
{!! $errors->first($fieldname, '<div class="col-md-8 col-md-offset-3"><span class="alert-msg"><i class="fa fa-times"></i> :message</span></div>') !!}
</div>
<!-- Department -->
<div id="assigned_department" class="form-group{{ $errors->has($fieldname) ? ' has-error' : '' }}"{!! (isset($style)) ? ' style="'.e($style).'"' : '' !!}>
{{ Form::label($fieldname, $translated_name, array('class' => 'col-md-3 control-label')) }}
<div class="col-md-7{{ ((isset($required) && ($required =='true'))) ? ' required' : '' }}">
<select class="department_select" data-endpoint="departments" data-placeholder="{{ trans('general.select_department') }}" name="{{ $fieldname }}" style="width: 100%" id="department_select">
#if ($department_id = Input::old($fieldname, (isset($item)) ? $item->{$fieldname} : ''))
<option value="{{ $department_id }}" selected="selected">
{{ (\App\Models\Department::find($department_id)) ? \App\Models\Department::find($department_id)->name : '' }}
</option>
#else
<option value="">{{ trans('general.select_department') }}</option>
#endif
</select>
</div>
{!! $errors->first($fieldname, '<div class="col-md-8 col-md-offset-3"><span class="alert-msg"><i class="fa fa-times"></i> :message</span></div>') !!}
</div>
You can use conditional rules to validate against your checkout type.
public function rules()
{
return [
'checkout_to_type_contract' => 'required',
'assigned_company' => 'required',
'assigned_store' => Rule::requiredIf(in_array(request('checkout_to_type_contract'),['department','store'])),
'assigned_department' => 'required_if:checkout_to_type_contract,department',
];
}

Multiple Checkbox Saving to DB 1 or 0

Creating multiple question checkboxes and I need to send two possible cases 1 or 0 to the database. However, it always sends the last one I click as 1 all the others 0. So for example, if a user clicks/checks the first one and the last I want to send to the database both 1 and the other two unchecked 0.
Controller
<?php
public function create($request)
{
foreach ($request['options'] as $key => $option) {
Answer::create([
'question_id' => $this->get(),
'text' => $option,
'correct' => $request['correct'] == $key ? 1 : 0
]);
}
}
View
#for($i = 1; $i<=4; $i++)
<div class="form-group {{ $errors->has('options.'.$i) ? ' has-error': '' }}" id="option{{ $i }}">
<div class="checkbox col-xs-2 control-label" style="margin-top: -2px">
<label>
<input id="cc" type="checkbox" name="correct" value="{{$i}}" {{ $i==1 ? 'checked' : '' }} >
<!--
{!! Form::hidden('correct',0) !!}
{!! Form::checkbox('correct',1,false) !!}
-->
</label>
</div>
<div class="col-xs-8">
<input type="text" name="options[{{ $i }}]" value="{{ old('options.'.$i) }}"
class="form-control" placeholder="#lang('general.option') {{ $i }}">
#if($errors->has('options.'.$i))
<div class="col-xs-12"></div>
<span class="help-block">
<strong>{{ $errors->first('options.'.$i) }}</strong>
</span>
#endif
</div>
</div>
#endfor
Either mention array of control for checkbox as below
<input id="cc" type="checkbox" name="correct[]" value="{{$i}}" {{ $i==1 ? 'checked' : '' }} >
change name="correct" to name="correct[]"
OR
give different name to each checkbox using incremental variable like
name="correct" to name="correct_".$i

Resources