I want to insert candidate language information into db and only for authenticated user. Candidate can add more languages. All info insert for the authenticated user.Authenticated Candidate can also
Here is my view code:
<form action="{{url('/candidate/addLanguage')}}" method="post">
#csrf
<!-- Education -->
<div class="form with-line">
<h5>Language Proficiency</h5>
<div class="form-inside">
<!-- Add Education -->
<div class="form boxed box-to-clone education-box">
<i class="fa fa-close"></i>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4"> Language</label>
<input type="text" name="txt_language[]" class="form-control" id="inputEmail4" placeholder="Language">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Reading</label>
<select name="txt_reading[]" id="" class="form-control">
<option value="#" selected>Choose..</option>
<option value="High">High</option>
<option value="Medium">Medium</option>
<option value="Low">Low</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4"> Writing</label>
<select name="txt_writing[]" id="" class="form-control">
<option value="#" selected>Choose..</option>
<option value="High">High</option>
<option value="Medium">Medium</option>
<option value="Low">Low</option>
</select>
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Speaking</label>
<select name="txt_speaking[]" id="" class="form-control">
<option value="#" selected>Choose..</option>
<option value="High">High</option>
<option value="Medium">Medium</option>
<option value="Low">Low</option>
</select>
</div>
</div>
</div>
<i class="fa fa-plus-circle"></i> Add Language
</div>
</div>
<button type="submit" class="btn btn-success btn-sm float-right">Submit</button>
</form>
My Controller :
public function addLanguage(Request $request){
$candidateID = Auth::guard('candidate')->user()->id;
if (count($request->txt_language) > 0){
foreach ($request->txt_language as $language => $l){
$data = array(
'candidate_id' => $candidateID,
'language' => $request->txt_language[$language],
'reading' => $request->txt_reading[$language],
'writing' => $request->txt_writing[$language],
'speaking' => $request->txt_speaking[$language],
) ;
Language::insert($data);
}
}
return redirect('/candidate/referencesForm')->with('success','Language Information Save Successfully..');
}
I get this error :
Attempt to assign property 'candidate_id' of non-object
Where I missing anything? How can I solve this error? Please Help
its "dd($request->all()); " output:
array:5 [▼
"_token" => "pcKuRe8xI8WzRYQefwY7GMw1Zo6vighrZ6k7PUNi"
"txt_language" => array:3 [▼
0 => "English"
1 => "Bangla"
2 => null
]
"txt_reading" => array:3 [▼
0 => "Medium"
1 => "Medium"
2 => "High"
]
"txt_writing" => array:3 [▼
0 => "High"
1 => "Low"
2 => "High"
]
"txt_speaking" => array:3 [▼
0 => "High"
1 => "High"
2 => "High"
]
]
Jquery Code:
$('.box-to-clone').show();
$('.add-box').on('click', function(e) {
e.preventDefault();
var newElem = $(this).parent().find('.box-to-clone:first').clone();
newElem.find('input').val('');
newElem.prependTo($(this).parent()).show();
var height = $(this).prev('.box-to-clone').outerHeight(true);
$("html, body").stop().animate({ scrollTop: $(this).offset().top-height}, 600);
});
$('body').on('click','.remove-box', function(e) {
e.preventDefault();
$(this).parent().remove();
});
Please follow the below format,
foreach ($request->txt_language as $language => $l){
$data = new Language;
$data->candidate_id => $candidateID,
$data->language => $request->txt_language[$language],
$data->reading => $request->txt_reading[$language],
$data->writing => $request->txt_writing[$language],
$data->speaking => $request->txt_speaking[$language],
$data->save();
}
Hope this would fix your issue. Let me know if you face further issue.
Try this :
public function addLanguage(Request $request){
$candidateID = Auth::guard('candidate')->user()->id;
if(!empty($candidateID)){
if (count($request->txt_language) > 0){
foreach ($request->txt_language as $language => $l){
Language::create([
'candidate_id' => $candidateID,
'language' => $l,
'reading' => $request->txt_reading[$language],
'writing' => $request->txt_writing[$language],
'speaking' => $request->txt_speaking[$language],
]);
}
}
return redirect('/candidate/referencesForm')->with('success','Language Information Save Successfully..');
}
abort(404);
}
Related
This is my basic form to create contacts in create.vue --
<div class="form-group mb-3 ">
<label class="form-label">Name</label>
<div>
<input type="text" class="form-control" placeholder="Enter Name" v-model="form.name" required>
</div>
</div>
<div class="form-group mb-3 ">
<label class="form-label">Contact Id</label>
<div>
<input type="text" class="form-control" placeholder="Enter Contact Id" v-
model="form.contact_id" required>
</div>
</div>
then I am giving the option to add address in the same form but which is not required. but if USER wants, while creating contact , user can add multiple addresses as well.
<div class="form-group row" v-for="(item, k) in form.addresses" :key="k" >
<label for="exampleFormControlInput1" class="form-label">Street 1:</label>
<div class="form-group mb-3">
<input class="form-control" type="text" v-model="item.street1" name="street1"
placeholder="Enter Street 1">
</div>
<div class="form-group mb-3">
<label for="exampleFormControlInput1" class="form-label">State</label>
<select class="form-control" v-model="item.state_id" name="state_id">
<option value="">Choose State</option>
<option value="1">Manitoba</option>
<option value="2">Winnipeg</option>
<option value="3">Punjab</option>
<option value="4">Other</option>
</select>
</div>
<div class="form-group mb-3">
<label for="exampleFormControlInput1" class="form-label">Country</label>
<select class="form-control" v-model="item.country_id" name="country_id">
<option value="">Choose Country</option>
<option value="1">Canada</option>
<option value="2">U.S</option>
<option value="3">India</option>
<option value="4">Other</option>
</select>
</div>
<div class="form-group mb-3">
<button class="btn btn-sm btn-danger" type="button"
#click="removeAddress(k)">Remove</button>
</div>
</div>
<div class="form-group row">
<div class="col-12">
<input class="btn btn-primary form-control" type="button" value="Add Another Address"
#click="addAddress()">
</div>
</div>
But whenever i am storing the data in database, it should be stored if only name has been given .
In the controller, my data is being fetched like this if i use return $request->all()--
{"name":"y","contact_id":"y","addresses":"[{"street1":"y","state_id":"1","country_id":"1"}]"}
Below is my controller code --
public function store(Request $request)
{
//return $request->all();
$contact = Contacts::create([
'name' => $request->name,
'company_id' => Auth::user()->company_id,
]);
$addresses= json_decode($request->addresses, true);
//return $addresses;
//[{"street1":"","state_id":"","country_id":""}]
if (! empty($addresses)) {
foreach($addresses as $ad) {
$address = new Address;
$address->contact_id = $contact->id;
$address->street1 = $ad['street1'];
$address->state_id = $ad['state_id'];
$address->country_id = $ad['country_id'];
$address->save();
}
}
how to check if variable values of street, state and country is null, it should not store data.
It is returning me error
Invalid datetime format: 1366 Incorrect integer value: '' for column clientchief_db.addresses.state_id at row 1 (SQL: insert into addresses (contact_id, street1, state_id, country_id, updated_at, created_at) values (14, , , , 2022-06-14 19:26:49, 2022-06-14 19:26:49))"
You should validate your request:
$request->validate([
'addresses' => ['required', 'array'],
'addresses.*.street1' => ['required', 'string'],
'addresses.*.state_id' => ['required', 'numeric'],
'addresses.*.country_id' => ['required', 'numeric'],
]);
If I understand it right
User can fill up just name & submit the form - data should be persisted in the database
User can fill up multiple address, but if user doesn't fill up complete details (street, state & country should be filled) for the address it should not be persisted in the database
One approach would be to
validate the address data, ONLY if user added address to the form
and return validation error if street1, state_id or country_id is null
public function store(Request $request)
{
//return $request->all();
$validated = $request->validate([
'name' => ['required', 'string'],
'addresses' => ['sometimes', 'array'],
'addresses.*.street1' => ['sometimes', 'required', 'string'],
'addresses.*.state_id' => ['sometimes', 'required', 'numeric'],
'addresses.*.country_id' => ['sometimes', 'required', 'numeric'],
]);
//The above will pass validation if name is filled as non empty string & addresses is not present in the request data
//But if the addresses is present in the request, it will fail if either of street1, state_id or country_id is null
$contact = Contacts::create([
'name' => $request->name,
'company_id' => Auth::user()->company_id,
]);
$addresses= json_decode($request->addresses, true);
//return $addresses;
//[{"street1":"","state_id":"","country_id":""}]
if (! empty($addresses)) {
foreach($addresses as $ad) {
$address = new Address;
$address->contact_id = $contact->id;
$address->street1 = $ad['street1'];
$address->state_id = $ad['state_id'];
$address->country_id = $ad['country_id'];
$address->save();
}
}
//return response
}
Laravel Docs - Validation - Validating When Present
I derived some data from jQuery in Laravel-5.8:
Model Class:
class HrLeaveRequest extends Model
{
protected $table = 'hr_leave_requests';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'company_id',
'employee_id',
'reason',
'leave_type_id',
'commencement_date',
'resumption_date',
'authorized_days',
'available_days',
'leave_status',
'no_of_days',
'relief_officer_id',
'contact_person_fullname',
'contact_person_phone',
'contact_person_address',
'created_by',
'created_at',
'updated_by',
'updated_at',
'is_active'
];
protected $dates = [];
protected $casts = [];
public function reliefofficer()
{
return $this->belongsTo('App\Models\Hr\HrEmployee','relief_officer_id');
}
public function leavetype()
{
return $this->belongsTo('App\Models\Hr\HrLeaveType','leave_type_id');
}
}
Controller
public function store(StoreLeaveRequestRequest $request)
{
$leaverequest = HrLeaveRequest::create([
'leave_type_id' => $request->leave_type_id,
'employee_id' => $userEmployee,
'commencement_date' => $commencementDate,
'resumption_date' => $resumptionDate,
'authorized_days' => $request->authorized_days,
'available_days' => $request->available_days,
'no_of_days' => $days,
'reason' => $request->reason,
'relief_officer_id' => $request->relief_officer_id,
'contact_person_fullname' => $request->contact_person_fullname,
'contact_person_phone' => $request->contact_person_phone,
'contact_person_address' => $request->contact_person_address,
'company_id' => Auth::user()->company_id,
'created_by' => Auth::user()->id,
'created_at' => date("Y-m-d H:i:s"),
'is_active' => 1,
]);
Session::flash('success', 'Leave Request is created successfully');
return redirect()->route('service.leave_requests.index');
}
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#leave_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
var op = "";
$.ajax({
type: 'get',
url: '{{ route('get.leavecounts.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
$('#authorized_leave_days').val(data.authorizedleavedays);
$('#available_leave_daysx').val(data.availableleavedays);
let sumAvailableDays = parseInt(data.authorizedleavedays) - parseInt(data.availableleavedays);
$("#available_leave_days").val(sumAvailableDays);
},
error:function(){
}
});
});
});
</script>
I derived 'authorized_days' and 'available_days' from the jQuery above and loaded the result into:
view
<form action="{{route('service.leave_requests.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="col-sm-4">
<div class="form-group">
<label>Leave Type:<span style="color:red;">*</span></label>
<select id="leave_type" class="form-control select2bs4" data-placeholder="Choose Leave Type" tabindex="1" name="leave_type_id" style="width: 100%;">
<option value="">Select Leave Type</option>
#if($leavetypes->count() > 0)
#foreach($leavetypes as $leavetype)
<option value="{{$leavetype->id}}">{{$leavetype->leave_type_name}}</option>
#endforeach
#endif
</select>
</div>
</div>
<input type="hidden" id="available_leave_daysx" class="form-control" value="0" >
<div class="col-sm-4">
<div class="form-group">
<label>Commencement Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="commencement_date" value="{{old('commencement_date')}}" min="{{Carbon\Carbon::now()->addDay()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Resumption Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="resumption_date" value="{{old('resumption_date')}}" min="{{Carbon\Carbon::now()->addDay()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Relief Officer:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Relief Officer" tabindex="1" name="relief_officer_id" style="width: 100%;">
<option value="">Select Relief Officer</option>
#if($reliefofficers->count() > 0)
#foreach($reliefofficers as $reliefofficer)
<option value="{{$reliefofficer->id}}">{{$reliefofficer->employee_code}} - {{$reliefofficer->first_name}} {{$reliefofficer->last_name}}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Reason</label>
<textarea rows="2" name="reason" class="form-control" placeholder="Enter Reason here" value="{{old('reason')}}"></textarea>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Contact Person Name:<span style="color:red;">*</span></label>
<input type="text" name="contact_person_fullname" placeholder="Enter contact person name here" class="form-control" value="{{old('contact_person_fullname')}}">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Contact Person Phone:<span style="color:red;">*</span></label>
<input type="number" name="contact_person_phone" placeholder="e.g. 23455996633" class="form-control" value="{{old('contact_person_phone')}}" pattern="[0-9]{13}" style="width: 100%;" maxlength="14">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Authorized Leave Days:</label>
<input type="number" id="authorized_leave_days" class="form-control authorized_days" name="authorized_days" value="{{old('authorized_days')}}" style="width: 100%;" disabled>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Available Leave Days:</label>
<input type="number" id="available_leave_days" class="form-control available_days" name="available_days" value="{{old('available_days')}}" style="width: 100%;" disabled>
</div>
</div>
<div class="card-footer">
<button type="submit" id="submit_create" class="btn btn-primary">{{ trans('global.save') }}</button>
'service.leave_requests.index')}}'" class="btn btn-default">Cancel
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#leave_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
var op = "";
$.ajax({
type: 'get',
url: '{{ route('get.leavecounts.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
$('#authorized_leave_days').val(data.authorizedleavedays);
$('#available_leave_daysx').val(data.availableleavedays);
let sumAvailableDays = parseInt(data.authorizedleavedays) - parseInt(data.availableleavedays);
$("#available_leave_days").val(sumAvailableDays);
},
error:function(){
}
});
});
});
</script>
And I see the data there clearly on my screen, but when I saved it I found null in each of the fields.
Then I did:
dd($leaverequest);
and I have this:
dd($leaverequest):
#attributes: array:17 [▼
"leave_type_id" => "1"
"employee_id" => 2
"commencement_date" => Carbon\Carbon #1586559600 {#804 ▶}
"resumption_date" => Carbon\Carbon #1587769200 {#790 ▶}
"authorized_days" => null
"available_days" => null
"no_of_days" => 11
"relief_officer_id" => "10"
"contact_person_fullname" => "assasasaddddd"
"contact_person_phone" => "08099448844"
"contact_person_address" => "xxzxzxzxz ddds"
"company_id" => 1
"created_by" => 2
"created_at" => "2020-04-10 22:10:41"
"is_active" => 1
"id" => 9
]
You can see:
"authorized_days" => null
"available_days" => null
How do I resolve this?
Thank you
I have some columns in my table that are not updating. I have checked everything many times and everything is spelled correctly and should be working.
I have the following in my view:
#section('content')
{{ csrf_field() }}
<h1 class='py-3'>List of Providers</h1>
<div class='form-group'>
<textarea name='survey_providers_list' type='' rows='10' class='form-control' id='' value = '{{ old('survey_providers_list') }}'></textarea>
<div>{{ $errors->first('survey_providers_list') }}</div>
</div>
<h1 class='py-3'>Comments & Questions</h1>
<p>Pleasee let us know any comments or questions you may have about our plan.</p>
<div class='form-group'>
<textarea name='comments' type='' rows='10' class='form-control' id='' value = '{{ old('comments') }}'></textarea>
<div>{{ $errors->first('comments') }}</div>
</div>
<h1 class='py-3'>Individual Health Insurance</h1>
<p>If you do not want to join our plan and would like some assistance evaluating your options in the Individual Health Insurance market, please select 'Yes' below and we will help you with this process.</p>
<div class='form-group'>
<select class='form-control' id='sel1' name='wants_ind_health_quote'>
<option value='Yes' >Yes</option>
<option value='No' >No</option>
</select>
<div>{{ $errors->first('wants_ind_health_quote') }}</div>
</div>
{{-- <h1 class='py-3'>Status</h1>
<div class='form-group'>
<select class='form-control' id='sel1' name='survey_status'>
<option value='In Progress' >In Progress</option>
<option value='Complete' >Complete</option>
</select>
<div>{{ $errors->first('survey_status') }}</div>
</div> --}}
{{-- Submit Button --}}
<div class="container">
<div class="row">
<div class="col text-right">
<button type="submit" name="action" value="next_step" class="btn btn-info">Submit</button>
</div>
</div>
</div>
#endsection
I have the following in my controller:
public function store(Request $request)
{
//
$test = Auth::check();
$userid = Auth::id();
$user = User::find($userid);
if ($test == false){
return redirect('/login');
}
else {
$data = request()->validate ([
'survey_providers_list' => '',
'wants_ind_health_quote' => '',
'comments' => '',
]);
$user->update($data);
return redirect ('/my-employer-plan');
}
}
I have used dd to verify the $user variable is working properly and the $data variable is pulling in the data. Both are working properly. However, the data in my table does not update. All the columns in the table are spelled correctly. All I can think of is that I cannot use the update function here for some reason.
Here is the dd($user):
App\User {#1368 ▼
#guarded: []
#fillable: array:3 [▶]
#hidden: array:2 [▶]
#casts: array:1 [▶]
#connection: "mysql"
#table: "users"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:13 [▼
"id" => 1
"name" => "Wruce Bayne"
"email" => "bobby#test.com"
"email_verified_at" => null
"password" => "$2y$10$cFtf.wT3BE0qbQ68oza8fuKAOYGyTULz1bhzAoL1O3rfHLt3BTI6i"
"active_plan_id" => null
"remember_token" => null
"created_at" => "2020-01-14 22:37:37"
"updated_at" => "2020-01-14 22:37:37"
"survey_providers_list" => null
"wants_ind_health_quote" => null
"comments" => null
"survey_status" => null
]
#original: array:13 [▶]
#changes: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#rememberTokenName: "remember_token"
}
first in User model add below code
protected $fillable = [
'survey_providers_list' ,
'wants_ind_health_quote' ,
'wants_ind_health_quote'
];
opssss Edit Code : you are filled user model with validation result !!!
$validation = request()->validate ([
'survey_providers_list' => '',
'wants_ind_health_quote' => '',
'comments' => '',
]);
$user->update($request->all());
// Post controller
public function update(Request $request, Post $post)
{
if($post->user_id != Auth::id())
{
Toastr::error('You are not authorized this post!!!!','Error');
return redirect()->back();
}
$this->validate($request,[
'title' =>'required',
// 'zip' => 'zip',
'image' => 'image',
'categories' => 'required',
'tags' => 'required',
'body' => 'required',
'live_demo' =>'required'
]);
$zipfile = $request->file('zip');
$slug = str_slug($request->title);
if (isset($zipfile))
{
$currentDate = Carbon::now()->toDateString();
$zipname = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $zipfile->getClientOriginalExtension();
if (!file_exists('storage/uploads/zip'))
{
mkdir('storage/uploads/zip',0777,true);
}
unlink('storage/uploads/zip/'.$post->zip);
$zipfile->move('storage/uploads/zip',$zipname);
}else{
$zipname = $post->zip;
}
$image = $request->file('image');
$slug = str_slug($request->title);
if (isset($image))
{
$currentDate = Carbon::now()->toDateString();
$imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1600,1066);
if (!file_exists('storage/uploads/post'))
{
mkdir('storage/uploads/post',0777,true);
}
unlink('storage/uploads/post/'.$post->image);
$image_resize->save('storage/uploads/post/'.$imagename);
}else{
$imagename = $post->image;
}
$post->user_id = Auth::id();
$post->title = $request->title;
$post->slug = str_slug($request->title);
$post->image = $imagename;
$post->zip = $zipname;
$post->body = $request->body;
$post->price = $request->price;
$post->live_demo = $request->live_demo;
if(isset($request->status))
{
$post->status =true;
}else
{
$post->status = false;
}
$post->is_approved = false;
$post->save();
$post->categories()->sync($request->categories);
$post->tags()->sync($request->tags);
Toastr::success('Post Successfully Updated:)','Success');
return redirect()->route('user.post.index');
}
}
// Route
Route::group(['as'=>'user.','prefix'=>'user','namespace'=>'Author','middleware'=>['auth','user']], function (){
Route::resource('post','PostController');
});
// Blade file
#extends('layouts.backend.app')
#section('title')
{{__('Post')}}
#endsection
#push('css')
<link href="{{asset('backend/plugins/bootstrap-select/css/bootstrap-select.css')}}" rel="stylesheet" />
#endpush
#section('content')
<div class="container-fluid">
<div class="container-fluid">
<div class="block-header"></div>
<!-- Basic Validation -->
<form action="{{route('user.post.update',$post->id)}}" method="POST" enctype="multipart/form-data">
#csrf
#METHOD('PUT')
<div class="row clearfix">
<div class="col-lg-8 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div class="header">
<h2>{{__('EDIT POST')}}</h2>
</div>
<div class="body">
<div class="form-group form-float">
<div class="form-line">
<input value="{{old('title')}}{{$post->title}}" type="text" class="form-control" name="title" required>
<label class="form-label">{{__('Post Title')}}</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input value="{{old('price')}}{{$post->price}}" type="text" class="form-control" name="price">
<label class="form-label">{{__('Price')}}</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-group">
<img src="{{ asset('storage/uploads/post/'.$post->image) }}" width="40px"height="30px" alt=""/>
<input type="file" class="form-control" name="image" >
<label class="form-label btn btn-primary">{{__(' Your Project ScreenShot')}}</label>
</div>
</div>
<div class="form-group">
<input type="checkbox" id="status" class="filled-in" name="status" value="1" {{ $post->status == true? 'checked' : ''}}>
<label for="status">{{__('Status')}}</label>
</div>
<div class="form-group form-float">
<div class="form-line">
<input value="{{old('live_demo')}} {{$post->live_demo}}" type="text" class="form-control" name="live_demo" required>
<label class="form-label">{{__('Live Demo')}}</label>
</div>
</div>
<div class="form-group">
<input type="file" class="form-control" name="zip" >
<label class="form-label btn btn-warning">{{__(' Your Project Upload')}}</label>
</div>
</div>
</div>
</div>
<div class="col-lg-4 col-md-12 col-sm-12 col-xs-12">
<div class="card ">
<div class="header bg-blue">
<h2 class="">{{__('Categrories & Tags')}}</h2>
</div>
<div class="body">
<div class="form-group form-float">
<div class="form-line" {{$errors->has('categories') ? 'fucused error' : '' }}>
<select name="categories[]" id="category" class="form-control show-tick" data-live-search="true" multiple>
<label for="category">{{__('Category Name')}}</label>
#foreach($categories as $category)
<option
#foreach($post->categories as $postCategory)
{{ $postCategory->id == $category->id? 'selected' : '' }}
#endforeach
value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group form-float">
<div class="form-line" {{$errors->has('tags') ? 'fucused error' : '' }}>
<select name="tags[]" id="tag" class="form-control show-tick" data-live-search="true" multiple>
<label for="tag">{{__('Tag Name')}}</label>
#foreach($tags as $tag)
<option
#foreach($post->tags as $postTag)
{{$postTag->id == $tag->id? 'selected' : ''}}
#endforeach
value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
</select>
</div>
</div>
<a class="btn btn-danger" href="{{route('user.post.index')}}">{{__('BACK')}}</a>
<button class="btn btn-primary waves-effect" type="submit">{{__('SUBMIT')}}</button>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div class="header">
<h2>{{__('Documanation')}}</h2>
</div>
<div class="body">
<textarea id="tinymce" name="body">
{{old('body')}} {!! $post->body!!}
</textarea>
</div>
</div>
</div>
</div>
</form>
</div>
#endsection
#push('js')
<script src="{{asset('backend/plugins/bootstrap-select/js/bootstrap-select.js')}}"></script>
<script src="{{ asset('backend/plugins/tinymce/tinymce.js') }}"></script>
<script>
$(function () {
//TinyMCE
tinymce.init({
selector: "textarea#tinymce",
theme: "modern",
height: 300,
plugins: [
'advlist autolink lists link image charmap print preview hr anchor pagebreak',
'searchreplace wordcount visualblocks visualchars code fullscreen',
'insertdatetime media nonbreaking save table contextmenu directionality',
'emoticons template paste textcolor colorpicker textpattern imagetools'
],
toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
toolbar2: 'print preview media | forecolor backcolor emoticons',
image_advtab: true
});
tinymce.suffix = ".min";
tinyMCE.baseURL = '{{ asset('backend/plugins/tinymce') }}';
});
</script>
#endpush
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'],
]
want to produce data exclusive to some field in database, so i add them in my view create . but there is an error cannot be null. even though the field is nullable.
this my view form.blade.php
<form action="" method="POST">
#csrf
<div class="box-body">
<div class="form-group">
<label for="">Project *</label>
<select class="form-control select2" style="width: 100%;" name="project_id">
<option>Select One</option>
#foreach($projects as $id => $project)
<option value="{{$id}}">{{$project}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">Story # Meeting Name *</label>
<input type="text" class="form-control" name="user_story">
</div>
<div class="form-group">
<label for="">Category *</label>
<select class="form-control select2" style="width: 100%;" name="task_category">
<option>Select One</option>
#foreach($task_categories as $task_category)
<option value="{{$task_category->task_category}}">{{$task_category->task_category}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">Estimated *</label>
<input type="text" class="form-control" name="estimated_time">
</div>
</div>
<div class="box-footer">
<a href="">
<button type="submit" class="btn btn-primary col-md-12" style="border-radius : 0px;">SAVE</button>
</a>
</div>
</form>
this my request
public function rules()
{
return [
'project_id',
'task_category',
'estimated_time',
'spent_time' => 'nullable',
'user_story' => 'nullable',
'story/meeting_name' => 'nullable',
'assign' => 'nullable',
'percentage' => 'nullable',
'lateness' => 'nullable',
'index' => 'nullable',
];
}
this my controller
public function store(OngoingRequest $request)
{
// dd($request->all());
$spentime = SpentTime::create([
'project_id' => request('project_id'),
'user_story' => request ('user_story'),
'task_category' => request('task_category'),
'estimated_time' => request('estimated_time'),
'spent_time' => request('spent_time'),
'assign' => request('assign'),
'story/meeting_name' => request('story/meeting_name'),
'percentage'=> request('percentage'),
'lateness' => request('lateness'),
'index'=> request('index'),
]);
return redirect()->route('plan.index');
}
and the error :
error
fields that i don't want to fill and not in the form must be filled. but im not need that.
set spent_time filed default value other wise set a nullable value
$table->string('spent_time')->nullable();
$table->boolean('spent_time')->default(0);