I'm trying to update a field after submitting in the following form:
<form action="{{ route("comments.update") }}" method="post">
#csrf
<input type="hidden" name="commentIDToEdit" id="commentID">
<div class="md-form mb-5">
<i class="fas fa-comment"></i>
<label for="toEditComment"></label>
<textarea name="toEditCommentary" id="toEditComment" cols="3" rows="5" style="resize: none"
class="form-control"></textarea>
</div>
<div class="modal-footer d-flex justify-content-center">
<button type="submit" class="btn btn-default">Modificar</button>
</div>
</form>
I have the CommentsController, where I process the data from the form. Here is the code:
public function updateComment()
{
request()->validate([
"toEditCommentary" => "min:10|max:500"
]);
if (Session::has("username") && getWarningCount(User::whereUsername(session("username"))->value("email")) > 0) {
Caveat::where("commentID", request("commentIDtoEdit"))
->update(["updatedComment" => request("toEditCommentary")]);
} else {
die("No se cumple la condición");
}
if (Comment::where("commentID", request("commentIDToEdit"))->exists()) {
Comment::where("commentID", request("commentIDToEdit"))
->update(["commentary" => request("toEditCommentary")]);
}
return back();
}
Curiosly, the comment is updated in his table, but not the warning. I was thinking in the fillable property in the model, but I don't have it, instead this, I have the following code:
protected $guarded = [];
const UPDATED_AT = null;
const CREATED_AT = null;
Your hidden input is named commentIDToEdit, but in the Controller you fetch the Caveat using request("commentIDtoEdit") (different case).
What you wrote:
Caveat::where("commentID", request("commentIDtoEdit"))
What you should have done: (note the different casing)
Caveat::where("commentID", request("commentIDToEdit"))
This is because in the view, the input name is commentIDToEdit, not commentIDtoEdit.
Related
I am trying to update the image into database but unfortunately, the image is not updating into the database how to fix it. please help me thanks.
Controller
public function updateslider(Request $request, $id)
{
$this->validate($request, [
'select_image' => 'required'
]);
$image = $request->file('select_image');
$extension = $image->getClientOriginalExtension();
Storage::disk('cms')->put(
$image->getFilename() . '.' . $extension,
File::get($image)
);
$content = new Sliders;
if ($request->file('select_image')) {
$content->slider_image = $image->getFilename() . '.' . $extension;;
$updaterecord = sliders::where(['id' => $content->id])->update(['slider_image' =>
$content]);
return back()->with('success', 'Image Updated Successfully')->with('path', $updaterecord);
}
}
HTML view
<form method="post" action="
{{route('update.action',$myslider->id)}}"
enctype="multipart/form-data" >
#csrf
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="header-title">Image Upload</h4>
<input type="file" name="select_image" value="
{{config('e_soft.file_url').$myslider->slider_image}}"
class="dropify" data-height="300" />
</div> <!-- end card-body-->
</div> <!-- end card-->
<div class="page-title-right">
<button type="submit" id="update" class="btn btn-danger
waves-effect waves-light col-lg-1">Update</button>
</div>
</div>
<!-- end row -->
</form>
Ok so I think your problem is that you want to set default value for <input type="file"> which is not possible. for security reasons you can't set default value for <input type="file"> so in your case you can check if there is a new image file you put the new one otherwise you just reassign previous slider image here is an example:
$slider = Sliders::findOrFail($id);
if (! empty($request->file('select_image'))) {
$content->slider_image = $image->getFilename().'.'.$extension;;
} else {
$content->slider_image = $slider->slider_image;
}
So as you can see first we check if there is a new file if so we assign new one otherwise we use the old one.
I need your help. I don't know how to import the excel file. I mean I don't understand where to put this users.xlsx and how to get its directory
public function import()
{
Excel::import(new UsersImport, 'users.xlsx');
return redirect('/')->with('success', 'All good!');
}
its simple on mattwebsite you need a controller like below :
public function importExcel(Request $request)
{
if ($request->hasFile('import_file')) {
Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
foreach ($reader->toArray() as $key => $row) {
// note that these fields are completely different for you as your database fields and excel fields so replace them with your own database fields
$data['title'] = $row['title'];
$data['description'] = $row['description'];
$data['fax'] = $row['fax'];
$data['adrress1'] = $row['adrress1'];
$data['telephone1'] = $row['telephone1'];
$data['client_type'] = $row['client_type'];
if (!empty($data)) {
DB::table('clients')->insert($data);
}
}
});
}
Session::put('success on import');
return back();
}
and a view like this :
<form
action="{{ URL::to('admin/client/importExcel') }}" class="form-horizontal" method="post"
enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label class="control-label col-lg-2">excel import</label>
<div class="col-lg-10">
<div class="uploader"><input type="file" name="import_file" class="file-styled"><span class="action btn btn-default legitRipple" style="user-select: none;">choose file</span></div>
</div>
</div>
<button class="btn btn-primary">submit</button>
</form>
and finally a route like below :
Route::post('admin/client/importExcel', 'ClientController#importExcel');
I have been unable to get the validation to work on an edit model-view that has data bound to it in the activate method of its view-model.
I have a created.ts which works on an object with the same fields. This file has almost the same code - the exception is that since this one is a create, no data needs to be loaded to it. In this case, the validation is working properly.
If I comment the code that loads the data for the edit model-view - in the activate method - the validation works properly.
Needless to say I am new to SPA, Aurelia and TypeScript and need some help!!
Below is the code in edit.ts
import { ContactRepository } from "./contactRepository";
import { autoinject } from "aurelia-framework";
import { ContactForEditDto } from "./contactForEditDto";
import { json } from "aurelia-fetch-client";
import { inject, NewInstance } from "aurelia-dependency-injection";
import { ValidationRules, ValidationControllerFactory, validateTrigger,
Validator } from "aurelia-validation";
#autoinject
export class Edit {
public saveStatusMessage: string;
public isSaved: number = -1;
private controller = null;
private validator = null;
public canSave: boolean = false;
constructor(public contactForEdit: ContactForEditDto, private repository:
ContactRepository, private controllerFactory: ValidationControllerFactory,
public contactFullName: string, validator: Validator) {
console.log("starting edit controller");
this.controller = controllerFactory.createForCurrentScope(validator);
this.controller.validateTrigger = validateTrigger.changeOrBlur;
this.validator = validator;
this.controller.subscribe(event => this.validateWhole());
ValidationRules
.ensure((c: ContactForEditDto) => c.contactFirstName)
.displayName("First Name")
.required().withMessage("\${$displayName} cannot be empty.")
.maxLength(50).withMessage("\${$displayName} cannot have more than 50 characters.")
.ensure((c: ContactForEditDto) => c.contactLastName)
.displayName("Last Name")
.required().withMessage("\${$displayName} cannot be empty.")
.maxLength(50).withMessage("\${$displayName} cannot have more than 50 characters.")
.ensure((c: ContactForEditDto) => c.contactEmailAddress)
.displayName("Email Address")
//.required().withMessage("\${$displayName} cannot be empty.")
.email().withMessage("\${$displayName} needs to be in a correct email address format.")
.maxLength(50).withMessage("\${$displayName} cannot have more than 50 characters.")
.ensure((c: ContactForEditDto) => c.contactPhoneNumber)
.displayName("Phone Number")
.required().withMessage("\${$displayName} cannot be empty.")
.maxLength(12).withMessage("\${$displayName} cannot have more than 12 characters.")
.matches(/\d{3}-\d{3}-\d{4}/).withMessage("'${$value}' is not a valid \${$displayName}. Please enter a phone in the format xxx-xxx-xxxx")
.on(ContactForEditDto);
}
// source https://www.jujens.eu/posts/en/2017/Jan/24/aurelia-validation/
workaround 3
validateWhole() {
this.validator.validateObject(this.contactForEdit)
.then(results => this.canSave = results.every(result => result.valid));
}
// Returning data from here because I can return a promise
// and let the router know when i have retrieved my initial data.
// Activate receives a params object as defined in the route.
activate(params) {
console.log("ACTIVATE ON EDIT PARAMS:" + params);
this.repository
.getById(params.id)
.then(data => {
console.log(data);
this.contactForEdit = data;
this.contactFullName = this.contactForEdit.contactLastName + ", " +
this.contactForEdit.contactFirstName; // This needs to come from a method
in
contact.
});
}
edit() {
this.saveStatusMessage = "";
this.isSaved = -1;
// This will be an edit
if (this.contactForEdit.contactId >= 1) {
this.repository
.update(this.contactForEdit)
.then(response => {
if (((response.status == 201) || (response.status == 204))
&& (response.ok == true)) {
this.isSaved = 1;
this.saveStatusMessage = "Successfully saved the contact";
}
else {
this.isSaved = 0;
//response.json().then(json => this.retVal = json);
//TODO: get more details about the error.
if (response.status == 400) {
this.saveStatusMessage = "Unable to save the contact. Please make sure that you entered correct values for every field and try again.";
}
else {
this.saveStatusMessage = "Unable to save the contact.";
}
}
});
}
}
clearContactFields() {
this.contactForEdit = new ContactForEditDto(-1, "", "", "", "");
}
}
Below is the code in edit.html
<template>
<form id="editContact" submit.delegate="edit()">
<!-- placeholder for status messages. If equal to 1 display it. If equals to
-1 or 1 hide this.-->
<div id="successStatusMessage" class.bind="isSaved == 1 ? 'visible' :
'hidden'">
<div id="divSuccessMessage" class="alert alert-success">
×
<!--<span class="glyphicon glyphicon glyphicon-ok" aria-hidden="true">
</span> TODO: How to get the glyphicon working? -->
<span class="sr-only"> Success:</span> ${saveStatusMessage}
</div>
</div>
<!-- placeholder for status messages. If equal to 0 is in error, so dislay error message. if equals to -1 or 1 hide this.-->
<div id="errorStatusMessage" class.bind="isSaved == 0 ? 'visible' : 'hidden'">
<!-- placeholder for status messages. -->
<div id="divErrorMessage" class="alert alert-danger">
×
<!-- <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> TODO: class="glyphicon glyphicon-exclamation-sign" how to get these in here for class? -->
<span class="sr-only"> Error:</span> ${saveStatusMessage}
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-title">
<!--<div if.bind="isCreate">
"Create a Contact"
</div>
<div if.bind="!isCreate">
Edit ${contactForEdit.contactFirstName}
</div>-->
${ "Edit " + contactFullName }
</div>
</div>
<div class="panel-body">
<div class="form-horizontal">
<div class="form-group" validation-errors.bind="editFirstNameErrors"
class.bind="editFirstNameErrors.length ? 'has-error' : ''">
<label class="control-label col-md-2">First Name: </label>
<div class="col-md-10">
<input type="text"
placeholder="First Name"
class="form-control"
value.bind="contactForEdit.contactFirstName & validate" required /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editFirstNameErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<div class="form-group" validation-errors.bind="editLastNameErrors"
class.bind="editLastNameErrors.length ? 'has-error' : ''">
<label class="control-label col-md-2">Last Name: </label>
<div class="col-md-10">
<input type="text"
placeholder="Last Name"
class="form-control"
value.bind="contactForEdit.contactLastName & validate" required /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editLastNameErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<div class="form-group" validation-errors.bind="emailErrors"
class.bind="editEmailErrors.length ? 'has-error' : ''">
<label for="emailAddress" class="control-label col-md-2">Email: </label>
<div class="col-md-10">
<input id="emailAddress"
type="text"
placeholder="Email Address (format: email#domain.com)"
class="form-control"
value.bind="contactForEdit.contactEmailAddress & validate" /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editEmailErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<div class="form-group" validation-errors.bind="editPhoneErrors"
class.bind="editPhoneErrors.length ? 'has-error' : ''">
<label class="control-label col-md-2">Phone: </label>
<div class="col-md-10">
<input type="text"
placeholder="Phone Number (format: xxx-xxx-xxxx)"
class="form-control"
value.bind="contactForEdit.contactPhoneNumber & validate" required /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editPhoneErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<button type="submit" class="btn btn-default ${canSave ? '' : 'disabled'}">
<!-- Look at click.dependent when there are child with buttons calling this.-->
Save
</button>
<!-- AA-10-17-17 - replaced with errors per input field. <ul for.bind="controller.errors">
<li repeat.for="error of controller.errors" style="color:red">
${error.message}
</li>
</ul>-->
</div>
</div>
</div>
</form>
<div>
<a route-href="route: home"
class="btn btn-default">
Back to list
</a>
</div>
</template>
I expect it's because of this code:
.getById(params.id)
.then(data => {
console.log(data);
this.contactForEdit = data;
your validation is against a ContactForEditDto object, but my guess is your repository is returning a JSON object cast to a ContactForEditDto, so it's not actually a class at all.
Try something like
console.log(data);
this.contactForEdit = new ContactForEditDto(data.id, data.firstname ..etc..);
or
console.log(data);
this.contactForEdit = Object.assign(new ContactForEditDto(), data);
We just had a similar problem and solved it by setting up our validations after assigning the remote data to our local field. In your code, you'd set up your validation rules after this.contactForEdit = data;
UPDATE
I just found the problem here, it is typo at $instID = $request->insititution;
It should be $instID = $request->institution;
Thanks for all your helps..
UPDATE
I trying to insert to CRConfigDetail Model / table, but first I need to get my CRConfigID from CRConfig Model / Table with specific rules. So I can get the CRConfigID and put it to CRConfigDetail column.
But every time I trying to retrieve, it always give empty data even I already have data at my database. In other Controller I can retrieve data with similar rules.
Am I do something wrong with logic? Because I don't see any errors.
Here is my HTML / form:
<form action="doInsertSCC" method="POST" enctype="multipart/form-data" id="scheduleDetailForm">
{{csrf_field()}}
<div class="form-group">
<label for="institution">Institution</label>
<select name="institution" class="form-control" id="institution">
</select>
</div>
<div class="form-group">
<label for="acadCareer">Academic Career</label>
<select name="acadCareer" class="form-control" id="acadCareer">
</select>
</div>
<div class="form-group">
<label for="period">Period</label>
<select name="period" class="form-control" id="period">
</select>
</div>
<div class="form-group">
<label for="department">Department</label>
<select name="department" class="form-control" id="department">
</select>
</div>
<div class="form-group">
<label for="fos">Field of Study</label>
<select name="fos" class="form-control" id="fos">
</select>
</div>
<div class="form-group">
<label for="scc">Lecturer's ID - Name</label>
<select name="scc" class="form-control" id="scc">
</select>
</div>
<button type="submit" class="btn btn-default">Assign SCC</button>
<div id="search" class="btn btn-default">Search</div>
</form>
Here is my Route to access my Controller
Route::post('/doInsertSCC', "ScheduleController#insertSCC");
And here is my ScheduleController
public function insertSCC(Request $request){
$this->validate($request, [
'scc' => 'required'
]);
$instID = $request->insititution;
$acadID = $request->acadCareer;
$termID = $request->period;
$depID = $request->department;
$rule = ['institutionID' => $instID, 'acadCareerID' => $acadID, 'termID' => $termID, 'departmentID' => $depID];
$crConfig = CRConfig::where($rule)->first();
if( !empty($crConfig) ){
foreach ($crConfig as $cr) {
$crConfigID = $cr->CRConfigID;
}
$schedule = new CRConfigDetail;
$schedule->status = 'Pending';
$schedule->numRevision = 0;
$schedule->FOSID = $request->fos;
$schedule->SCC = $request->scc;
$schedule->CRConfigID = $crConfigID;
$schedule->save();
return redirect("AssignSCC")->with('status', 'Add SCC success!');
}else{
return redirect("AssignSCC")->with('status', 'Add schedule first!');
}
}
I already check my rules data are match with my CRConfig table's data (using console.log()
Everytime I submit this form, I will do the "else" and redirect with "Add schedule first!" message.
Actually, it does accept an array, but the array should be formatted as such..
$rule = [
['institutionID', '=', $instID],
['acadCareerID', '=', $acadID],
['termID', '=', $termID],
['departmentID', '=', $depID]
];
Source: https://laravel.com/docs/5.4/queries#where-clauses
use the below one
$crConfig = CRConfig::where('institutionID' , $instID)
->where('acadCareerID' , $acadID)
->where('termID', $termID)
->where('departmentID', $depID)
->first();
instead of
$rule = ['institutionID' => $instID, 'acadCareerID' => $acadID, 'termID' => $termID, 'departmentID' => $depID];
$crConfig = CRConfig::where($rule)->first();
You can check the query built at the backend by getting the query log, for this you have to enable the query log before the query gets built and get the query log after the query gets built both query log methods belongs to DB facade
\DB::enableQueryLog();
\DB::getQueryLog();
I get no obvious errors when adding a new job to my database.
My industry job goes into the jobs table but the relationship with divisions in my join table goes nowhere. I just can't see where I'm going wrong
JOIN TABLE
division_industryjob
division_id
industryjob_id
divisions
id
division_name
industryjobs
id
job_title
MODELS
Division.php
<?php
class Division extends \Eloquent {
protected $table = 'divisions';
/**
* Industry Jobs relationship
*/
public function industryjobs()
{
return $this->belongsToMany('IndustryJob');
}
}
IndustryJob.php
<?php
class IndustryJob extends \Eloquent {
protected $table = 'industryjobs';
public function divisions()
{
return $this->belongsToMany('Division');
}
}
ROUTES
Route::get('industry-jobs/add', 'AdminController#getCreateIndustryJob');
Route::post('industry-jobs/add', 'AdminController#postCreateIndustryJob')
CONTROLLER
// Create Industry - Get (empty form - new entry)
public function getCreateIndustryJob()
{
View::share('page_title', 'Create a new Industry Job Role');
View::share('sub_page_title', 'Ex: Mechanical Technician');
return View::make('admin/industry-jobs/create');
}
// Create Industry - Post
public function postCreateIndustryJob()
{
//validate user input
$rules = array(
'job_title' => 'Required|Min:3|Max:80'
);
$validation = Validator::make(Input::all(), $rules);
If ($validation->fails())
{
return Redirect::to('/admin/industry-jobs/add')->withErrors($validation);
} else {
$industryjob = new IndustryJob;
$industryjob->job_title = Input::get('job_title');
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
if (isset($input['divisions'])) {
foreach ($input['divisions'] as $divId) {
$div = Division::find($divId);
$industryjob->divisions()->save($div);
}
}
$industryjob->save();
return Redirect::to('/admin/industry-jobs')->with('message', 'Industry Job created successfully');
}
}
FORM
<form class="form-horizontal" method="post" autocomplete="off">
<!-- Industry Job Title -->
<div class="form-group">
<label class="col-md-2 control-label" for="industry_name">Industry Job Title (*)</label>
<div class="col-md-10">
<input class="form-control" type="text" name="job_title" id="job_title" value="" />
</div>
</div>
<!-- ./ Industry Job Title -->
<!-- Industry Type -->
<div class="form-group">
<label class="col-md-2 control-label" for="body">Related Division</label>
<div class="col-md-10">
<select name="divisions[]" id="divisions" size="6" class="form-control" multiple>
#foreach (Division::all() as $division)
<option value="{{ $division->id }}" >{{ $division->division_name }}</option>
#endforeach
</select>
</div>
</div>
<!-- ./ Industry Type -->
<!-- Form Actions -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-success">Create Job</button>
</div>
</div>
<!-- ./ form actions -->
</form>
You are saving the Parent model afterwards so it's not working. Save the Parent model before you save the Child Model, so it should be something like this:
$industryjob = new IndustryJob;
$industryjob->job_title = Input::get('job_title');
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
$industryjob->save();
Then save the related models using sync because it's many-to-many relationship and those related models are already created and available in the database:
if (isset($input['divisions'])) {
// Pass the array of ids to sync method
$industryjob->divisions()->sync($input['divisions']);
}
If you use the foreach loop then you may use something like this;
foreach ($input['divisions'] as $divId) {
$industryjob->divisions()->attach($divId);
}
Check more about inserting related models on Laravel website.