How can I solve " Invalid datetime format: 1366 Incorrect integer value" Exception in Laravel 7? - mysql

I'm quite new to Laravel, I would like to update a column in mySQL database named "client_id" the name of the table is "projects" I would like to insert this column when a Client creates a new Project, because the project belongs to the Client who created it. "client_id" is the Primary Key (id) in the table called "clients". There is a relationship between "clients" table and "projects" table. I have written some code to solve this problem but I'm getting this Exception and the "client_id" column is not updated.
Please help.
Store Method in my Controller:
/**
* Store a newly created Project in storage.
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'description' => 'required|string|max:255',
'start_date' => 'required|date',
'start_time' => 'required|string|max:10',
]);
$project = Project::create([
'name' => $request->name,
'description' => $request->description,
'start_date' => $request->start_date,
'start_time' => $request->start_time,
]);
$loggedinId = Auth::id();
$project->update(['created_by' => $loggedinId]);
$userId = $loggedinId;
$clientId = Client::where('user_id', '=', $userId)->pluck('id')->all();
DB::table('projects')->where('created_by', '=', $loggedinId)->update([ 'client_id' => $clientId]);
return redirect()->back()->with('message', 'You have successfully submitted your Job Card');
}
Relationship in my Client Model:
/**
* #return HasMany
*/
public function projects()
{
return $this->hasMany(Project::class);
}
Relationship in my Project Model:
/**
* #return BelongsTo
*/
public function client()
{
return $this->belongsTo(Client::class, 'client_id');
}
Form In my Blade View:
<form method="POST" action="{{ route('client-jobcard.store') }}">
#csrf
<div class="form-group row">
<div class="col-sm-8">
<label for="name">{{ __('Job Card Name') }}</label><span class="required">*</span>
<input id="name" type="text" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ old('name') }}" required autofocus>
#if ($errors->has('name'))
<span class="invalid-feedback">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-sm-8">
<label for="description">{{ __('Job Card Description') }}</label><span class="required">*</span>
<textarea class="form-control{{ $errors->has('description') ? ' is-invalid' : '' }}" id="description" rows="4" style="height: 150px;" name="description" value="{{ old('description') }}" required autofocus></textarea>
#if ($errors->has('description'))
<span class="invalid-feedback">
<strong>{{ $errors->first('description') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
<label for="start_date">Start Date</label><span class="required">*</span>
<input type="date" class="form-control" id="start_date" name="start_date" value="{{ old('start_date') }}" required>
</div>
<div class="col-sm-4">
<label for="submission_date">Start Time</label><span class="required">*</span>
<input type="text" class="form-control" id="start_time" name="start_time" value="{{ old('start_time') }}" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
<button type="submit" class="btn btn-primary">
{{ __('Submit') }}
</button>
</div>
</div>
</form>

This line:
$clientId = Client::where('user_id', '=', $userId)->pluck('id')->all();
will return a column, not the single ID ("2") that you want.
Then, when you assign it to client_id which is an integer, the ORM will render it as the string [2] instead of the number 2, and that will give you an error.
Either retrieve just the first tuple from Client, or extract $clientId[0] manually (wasteful and not recommended).
You also have a second error I had overlooked:
'created_by', '=', $loggedinId
The above means that created_by must be an integer value, but the text of the error implies SQL expects it to be a datetime. You seem to have a wrong definition in the database.

your time field is in string , it has to be changed , it is not the same format
can you try this instead

Related

Textarea with CKEditor not saving html tags on server side

I am using Laravel 8, MySQL, and CKEditor. I would like to ask what could possibly be causing a difference between my local and server.
On my local what I enter into the text editor will be saved to the DB along with the html tags.
While on the server, it will only save the text without the html tags
Below is my controller
public function store(Request $reqst){
$new_info = new Information;
$rules = array(
'title' => ['required', 'string', 'max:255'],
'content' => "required",
);
$this->validate($reqst, $rules);
$new_info->title = $reqst->title;
$new_info->content = $reqst->content;
$new_info->user_id = Auth::user()->id;
$new_info->save();
return redirect('/admin/informations');
}
Here is my blade
<form action="{{ route('informations/add-new-information/store') }}" method="POST" class="col-lg-12 mt-4">
#csrf
<div class="form-group">
<label for="title">Title: <span class="text-danger">*</span></label>
<input type="text" name="title" id="title" class="form-control #error('title') is-invalid #enderror" required placeholder="Maximum of 255 Characters">
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-group">
<label for="content">Content: <span class="text-danger">*</span></label>
<textarea name="content" id="content" cols="30" rows="10"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Add New Information</button>
</div>
</form>
<script src="https://cdn.ckeditor.com/ckeditor5/23.0.0/classic/ckeditor.js"></script>
<script>
ClassicEditor
.create( document.querySelector( '#content' ) )
.catch( error => {
console.error( error );
} );
</script>
I am trying to figure out why are the html tags not present on server side.
Thanks :)
*** UPDATE! ***
After doing php artisan config:cache, route:cache, and view:cache
The HTML tags are no longer being passed even on local.
you should add this script After the ckeditor.js script
<script>
CKEDITOR.replace('content');
</script>

Failed to store data in laravel 8

I'm making a form so that users can request to create a new account to the admin, but every time I try to send data, it always fails, even though I've checked every part of my code, can anyone help me?
the form code :
<form method="POST" action="{{ url('/request-akun/make-request') }}">
#csrf
<div class="form-group col-md-12">
<label for="name">Nama</label>
<input type="text" name="name" class="form-control" id="name">
</div>
<div class="form-group col-md-12">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" id="email">
</div>
<div class="form-group col-md-12">
<label for="password">Password</label>
<input type="text" name="password" class="form-control"
id="password">
</div>
<div class="form-group col-md-12">
<label for="password_confirm">Konfirmasi Password</label>
<input name="password_confirm" type="text" class="form-control"
id="password">
</div>
<button type="submit" class="btn btn-primary pull-right"
style="margin-right: 15px;">Request</button>
</form>
this is the controller :
public function requestAccount(Request $request){
$request->validate([
'name' => 'required|string|max:255',
'ra_instansi_id' => 'required',
'email' => 'required|string|email|max:255',
'password' => 'required',
'password_confirm' => 'required'
]);
if ($request->get('password') == $request->get('password_confirm')){
$data = new requestAkun();
$data->name = $request->get('name');
$data->ra_user_id = Auth::id();
$data->ra_instansi_id = Auth::user()->instansiID;
$data->email = $request->get('email');
$data->password = $request->get('password');
$data->status = "pending";
$data->save();
return Redirect::to('/request-akun/request-lists')->with('success','Request Berhasil dikirim');
} else {
return Redirect::to('/request-akun/request-lists')->with('error','Password tidak sama');
}
}
this is the model code:
class requestAkun extends Model
{
use HasFactory, Uuids;
protected $table = 'request_akun';
public $timestamps = true;
protected $fillable = [
'name',
'ra_instansi_id',
'ra_user_id',
'email',
'password',
'status'
];
}
this is the route :
Route::prefix('request-akun')->group(function(){
Route::post('/make-request',[userController::class,'requestAccount'])->name('make-request');
});
Error is you don't have ra_instansi_id input in your form.
Not showing any validation error message in your form so better show errors so you check which validation failed.
3.Instead of checking password match in if condition you can change input name password_confirm to password_confirmation so you can change like below
<input name="password_confirmation" type="text" class="form-control"
id="password_confirmation">
and in your validation
$validator=Validator::make($request->all(),[
'name' => 'required|string|max:255',
'ra_instansi_id' => 'required',
'email' => 'required|string|email|max:255',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
]);
dd($validator->errors());

How to Send Multiple Checkbox through migration in LARAVEL_7

I want to store the selected checks in a single variable and send it to the database, I am only using migrations, others that other data is sent in the migration.
Pd: I get this error by the array:
ErrorException
Array to string conversion
My template.
<form action="{{ route('save') }}" method="POST">
#csrf
<div class="row">
<div class="col-md-6 mt-5">
<select name="Sede" class="form-select" aria-label="Default select example">
<option selected name="Sede">Campus Sede</option>
<option value="Cancún">Cancún</option>
<option value="Chihuahua">Chihuahua</option>
</select>
</div>
<div class="col-md-6 mt-5">
<select name="Alcance" class="form-select" aria-label="Default select example">
<option selected name>Alcance</option>
<option value="Local">Local</option>
<option value="Nacional">Nacional</option>
</select>
</div>
<div class="col-md-6 mt-5">
<label for="">Nombre del Proyecto</label>
<input type="text" name="Nombre" class="form-control col-12">
</div>
<div class="col-md-6 mt-5">
<label for="">Cierre de Inscripciones</label>
<input data-date-format="yyyy/mm/dd" id="datepicker" name="Cierre" class="form-control col-12">
</div>
<div class="col-md-6 mt-5">
<input type="checkbox" name="Areas[]"id="ingenieria" value="Ingeniería" />
<label for="ingenieria">Ingeniería</label>
<input type="checkbox" name="Areas[]"id="humanidades" value="Humanidades" />
<label for="humanidades">Humanidades</label>
<input type="checkbox" name="Areas[]"id="negocios" value="Negocios" />
<label for="negocios">Negocios</label>
<input type="checkbox" name="Areas[]" id="salud" value="Salud" />
<label for="salud">Salud</label>
</div>
<div class="col-md-12 mt-5">
<label for="">Cual es el departamento donde impactara directamente el proyecto?</label>
<input type="text" name="P1" class="form-control col-12">
</div>
<div class="row form-group mt-5">
<button type="submit" class="btn btn-success col-md-2 offset-5">Guardar</button>
</div>
</form>
My controller:
public function save(Request $request){
$validator = $this->validate($request, [
'Sede'=> 'required|string|max:255',
'Alcance'=> 'required|string|max:255',
'Nombre'=> 'required|string|max:255',
'Cierre'=> 'required|date',
'Areas'=> 'required',
'P1'=> 'required|string|max:255',
'P2'=> 'required|string|max:255',
'P3'=> 'required|string|max:255',
'P4'=> 'required|string|max:255'
]);
$data = request()->except('_token');
Project::insert($data);
return back()->with('datosGuardados', 'Datos almacenados, Correctamente');
}
My Model:
class Project extends Model
{
protected $fillable = ['Sede','Alcance','Nombre','Cierre','Areas','P1','P2','P3','P4'];
protected $casts = [
'Areas' => 'array'
];
}
My migration:
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('Sede');
$table->string('Alcance');
$table->string('Nombre');
$table->date('Cierre');
$table->string('Areas');
$table->string('P1');
$table->string('P2');
$table->string('P3');
$table->string('P4');
$table->timestamps();
});
}
enter image description here
As you see the error is due to the checkbox that I don't know how to send it as a single array and store it in the database, I would appreciate any help. I was investigating and I did not find anything
$validator = $this->validate($request, [
'Sede'=> 'required|string|max:255',
'Alcance'=> 'required|string|max:255',
'Nombre'=> 'required|string|max:255',
'Cierre'=> 'required|date',
'Areas'=> 'required',
'P1'=> 'required|string|max:255',
'P2'=> 'required|string|max:255',
'P3'=> 'required|string|max:255',
'P4'=> 'required|string|max:255'
]);
// Add this line
$area = [];
foreach ($request->Areas as $key => $value) {
$area[$key] = $value;
}
// And then save in database with $area created using foreach.
Use this 'Areas.*'=> 'required', for validating the checkbox generally, moreover to insert the data under Areas, you can insert it via converting by json_encode($request->Areas);

How to render multiple times to same template in a single function block

I want to render multiple times in each if statement to same template. But in the HTML template it's only taking the last rendered statement.
I passed the context in the form of dictionary in the return render statement.
views.py
if not match :
#messages.info(requests,'Invalid')
return render(requests, 'validate/home1.html', {'title' : 'Invalid mail'})
if not country_code:
return render(requests, 'validate/home1.html', {'title3' : 'Enter correct country code'})
if not pwd_match :
return render(requests, 'validate/home1.html', {'title1' : 'Enter password again'})
if not phone :
return render(requests, 'validate/home1.html', {'title2' : 'Enter 10 digit number'})
home1.html
<form id="waterform" method="post" autocomplete="off">
{% csrf_token %}
<div class="formgroup" id="name-form">
<label for="name">Country Code*</label>
<input type="text" id="name" name="name" required />
</div>
<div>
<p style="color: red; margin-left: 10px">{{ title3 }}</p>
</div>
<div class="formgroup" id="email-form">
<label for="email">Your e-mail*</label>
<input type="text" id="email" name="email" required />
</div>
<div>
<p style="color: red; margin-left: 10px">{{ title }}</p>
</div>
<div class="formgroup" id="email-form">
<label for="password">Your password*</label>
<input type="text" id="pwd" name="pwd" required />
</div>
I want to display each condition (title, title1, title2) which satisfies the if blocks.
Something like this. It will put all the errors in one dictionary and when rendering, if the error doesn't exist, will just display an empty ''.
a=''
b=''
c=''
d=''
if not match :
a = 'invalid mail'
if not country_code:
b = 'Enter correct country code'
if not pwd_match :
c = 'Enter password again'
if not phone :
d = 'entire ten digit number'
errors = {'title':a, 'title1': b, 'title2': c, 'title3':d}
return render(requests, 'validate/home1.html', errors)
The execution will stop in the first match.
You should make all the validations before rendering and send the errors to the view, then write all those conditions on the template side.

How to insert two serial numbers with one insert into

I try to make it possible to lend two books at once my problem is that only one value gets forwarded. The form looks like this:
In the view I tried to rename the field to "serial number2" because I thought that he just ignored the second serial number because of the same name.
This is my View:
<div class="card">
<div class="card-header">{{ __('Lend a book') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('borrow.store') }}">
#csrf
<div class="form-group row">
<label for="serialnumber" class="col-md-4 col-form-label text-md-right">{{ __('Please scan the Serialnumber of the book') }}</label>
<div class="col-md-6">
<input id="serialnumber" type="text" class="form-control{{ $errors->has('serialnumber') ? ' is-invalid' : '' }}" name="serialnumber" value="{{ old('serialnumber') }}" required #if (Session::has('autofocus')) autofocus #endif>
#if ($errors->any())
<div class="alert alert-danger">The book is not in stock.
<ul>
</ul>
</div>
#endif
</div>
</div>
<div class="form-group row">
<label for="serialnumber" class="col-md-4 col-form-label text-md-right">{{ __('') }}</label>
<div class="col-md-6">
<input id="serialnumber" type="text" class="form-control{{ $errors->has('serialnumber') ? ' is-invalid' : '' }}" name="serialnumber" value="{{ old('serialnumber') }}" required #if (Session::has('autofocus')) autofocus #endif>
#if ($errors->any())
<div class="alert alert-danger">The book is not in stock..
<ul>
</ul>
</div>
#endif
</div>
</div>
<div class="form-group row">
<label for="comment" class="col-md-4 col-form-label text-md-right">{{ __('comment') }}</label>
<div class="col-md-6">
<!-- <input id="ma_id" type="text" class="form-control{{ $errors->has('ma_id') ? ' is-invalid' : '' }}" value="{{ old('ma_id') }}" required> -->
<input id="comment" type="text-field" class="form-control" name="comment" placeholder="Test">
#if ($errors->has('comment'))
<span class="invalid-feedback">
<strong>{{ $errors->first('comment') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="ma_id" class="col-md-4 col-form-label text-md-right">{{ __('scan membercard to identify yourself') }}</label>
<div class="col-md-6">
<!-- <input id="ma_id" type="text" class="form-control{{ $errors->has('ma_id') ? ' is-invalid' : '' }}" value="{{ old('ma_id') }}" required> -->
<input id="ma_id" type="password" class="form-control" name="ma_id" required>
#if ($errors->has('ma_id'))
<span class="invalid-feedback">
<strong>{{ $errors->first('ma_id') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('send') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
This is my Controller:
public function store(bookRequest $request)
{
//if( !book::find($request->get('serialnumber'))->exists() ) {
$this->middleware('guest');
request()->validate([
'serialnumber' => 'required',
'serialnumber' => 'required',
'ma_id' => 'required'
]);
book::create($request->all());
return redirect()->route('book.index');
}
There is no error but the problem is that he writes only one serial number into the database as described above and completely ignores the other one that comes into the second field. My question is what I have to adjust so that the second serial number with the same data can be written into the database.
You cannot have two items with the same name (for example serialnumber) in the same form, otherwise only one value is going to be processed. Please check the inspection tool in the browser. If you need multiple inputs with the same "name" append [] to the name (for example name=serialnumber[]).
More info at HTML 5 spec
In the other hand, you have multiple items with the same ID. That's another issue to fix in some point.
Once you have your data in the controller you will have to generate your insert data accordingly
$requestData = $request->validated();
$data = [
[
'serialnumber' => $requestData['serialnumber'][0],
'comment' => $requestData['comment'],
'ma_id' => $requestData['ma_id']
],
[
'serialnumber' => $requestData['serialnumber'][1],
'comment' => $requestData['comment'],
'ma_id' => $requestData['ma_id']
]
];
Book::insert($data);
Make input's name as array.
Replace name="serialnumber" with name="serialnumber[]". When form is submitted, you will receive an array with both serial numbers.