make certain creation between form and field in database in laravel - laravel

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);

Related

Check dynamic variable of an array contains value or not in php

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

zoom integration MacsiDigital / laravel-zoom Call to a member function get() on null

i am using MacsiDigital/laravel-zoom package but the problem is Call to a member function get() on null i dont know why and i made everything correct
i am using MacsiDigital/laravel-zoom package but the problem is Call to a member function get() on null i dont know why and i made everything correct
here is my code
this is my create blade
<form method="post" action="{{ route('online_classes.store') }}" autocomplete="off">
#csrf
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="Grade_id">{{ trans('Students_trans.Grade') }} : <span
class="text-danger">*</span></label>
<select class="custom-select mr-sm-2" name="grade">
<option selected disabled>{{ trans('Parent_trans.Choose') }}...</option>
#foreach ($Grades as $Grade)
<option value="{{ $Grade->id }}">{{ $Grade->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="Classroom_id">{{ trans('Students_trans.classrooms') }} : <span
class="text-danger">*</span></label>
<select class="custom-select mr-sm-2" name="class">
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="section_id">{{ trans('Students_trans.section') }} : </label>
<select class="custom-select mr-sm-2" name="section_id">
</select>
</div>
</div>
</div><br>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>عنوان الحصة : <span class="text-danger">*</span></label>
<input class="form-control" name="topic" type="text">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>تاريخ ووقت الحصة : <span class="text-danger">*</span></label>
<input class="form-control" type="datetime-local" name="start_time">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>مدة الحصة بالدقائق : <span class="text-danger">*</span></label>
<input class="form-control" name="duration" type="text">
</div>
</div>
</div>
<button class="btn btn-success btn-sm nextBtn btn-lg pull-right"
type="submit">{{ trans('Students_trans.submit') }}</button>
</form>
and this is my fillable model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class online_class extends Model
{
protected $fillable = [
'grade_id',
'classroom_id',
'section_id',
'topic',
'start_at',
'duration',
'user_id',
'meeting_id',
'start_url',
'join_url',
'password',
];
public function user(){
return $this->belongsTo(User::class,'user_id');
}
}
and this is my store method in controller
public function store(Request $request)
{
$user = Zoom::user()->first();
$meeting = Zoom::meeting()->make([
'topic' => $request->topic,
'duration' => $request->duration,
'password' => $request->password,
'start_time' => $request->start_time,
'timezone' => 'Africa/Cairo',
]);
$meeting->settings()->make([
'join_before_host' => false,
'approval_type' => 1,
'registration_type' => 2,
'enforce_login' => false,
'waiting_room' => false,
]);
online_class::create([
'grade_id' => $request->grade,
'classroom_id' => $request->class,
'section_id' => $request->section_id,
'topic' => $request->topic,
'start_at' => $request->start_time,
'duration' => $meeting->duration,
'user_id' => Auth::user()->id,
'meeting_id' => $meeting->id,
'start_url' => $meeting->start_url,
'join_url' => $meeting->join_url,
'password' => $meeting->password,
]);
return $user->meetings()->save($meeting);
}

How to Retain same value entered in input fields after laravel validation fails

My Blade File Code :-
<div class="col-md-6">
<div class="form-group">
<label for="city">Assigned Hour<span class="text-danger">*</span></label>
<div class="dateBox">
<input type="number" name="assigned_hour[[]" class="form-control newAssignedHour" autocomplete="off" value="" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="city">Consumed Hour<span class="text-danger">*</span></label>
<div class="dateBox">
<input type="number" name="consumed_hours[[]" class="form-control newConsumedHour" autocomplete="off" value="" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group c-label datepicker-wrap">
<label for="city">Date<span class="text-danger">*</span></label>
<div class="dateBox">
<input type="text" name="date[]" class="form-control input-daterange newDate" id="dateInput" autocomplete="off" value="" required>
<span href="" class="dateCalender emp-cost-i">
<i class="fa fa-calendar"></i> </span>
</div>
</div>
</div>
my Controller :-
$valid = request()->validate([
'project_id' => 'required|int|exists:projects,project_id',
'email_id' => 'required|email',
'emp_id' => 'required|int|exists:contacts,employee_id',
'project_name' => 'required|string|exists:projects,name',
'GMWO' => 'required',
'employee_name' => 'required|string',
'newJobIds' => 'required|array',
'newJobNames' => 'required|array',
'newAssignedHours' => 'required|array',
'newConsumedHours' => 'required|array',
'newDates' => 'required|array'
]);
Can Anyone Suggest How to Retain the old Value for these fields. {{ old('field_name') }} that doesn't work for this.
thanks in Advance
Please try with the below method when validation gets failed and is redirected to form in the controller
->withInput()
For more reference see the below link
https://laravel.com/docs/9.x/responses#redirecting-with-input

Laravel, adding data to database after verifying ReCaptcha

I'm using ReCaptcha in my Laravel project, done it with this
tutorial.
I need to create a page where user can post his message after checking captcha.
I have created a modal dialog where user can fill in data like this :
<form class="form-horizontal" action="" method="post">
<div class="form-group error">
<label for="messageName" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="name" name="name" placeholder="Your name" value=""
ng-model="message.name" ng-required="true">
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageEmail" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control has-error" id="email" name="email" placeholder="E-mail" value=""
ng-model="message.email" ng-required="true">
<span class="help-inline"
ng-show="GBM.email.$invalid && GBM.email.$touched">Required</span>
</div>
</div>
<div class="form-group error">
<label for="messageLink" class="col-sm-3 control-label">Web</label>
<div class="col-sm-9">
<input class="form-control" rows="3" class="form-control has-error" id="web" name="web" placeholder="Link for your web" value="" ng-model="message.web" ng-required="false" >
</div>
</div>
<div class="form-group error">
<label for="messageText" class="col-sm-3 control-label">Comment</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" class="form-control has-error" id="comment" name="comment" placeholder="Your comment" value="" ng-model="message.text" ng-required="true" ></textarea>
<span class="help-inline"
ng-show="GBM.text.$invalid && GBM.text.$touched">Required</span>
</div>
</div>
{!! csrf_field() !!}
<!-- recaptcha -->
{{Request::is('contactd')}}
<div class="form-group">
<div class="col-md-9">
<div class="g-recaptcha" data-sitekey="{{env('GOOGLE_RECAPTCHA_KEY')}}"></div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-9 control-label"></label>
<div class="col-md-9">
<button type="submit" name="send" class="btn btn-primary btn-lg btn-block">Add new message <span class="fa fa-paper-plane-o"></span></button>
</div>
</div>
</form>
For a route I got it like this:Route::post('contact','ContactController#store');
And here is the problem, in my controller i got this code to verify captcha:
public function store(ReCaptchataTestFormRequest $request){
return "Captcha done right! ";}
And this code to save data to database
public function store(Request $request)
{
$this->validate($request, [ 'name' => 'required|max:255' ]);
$this->validate($request, [ 'email' => 'required | email' ]);
$this->validate($request, [ 'comment' => 'required' ]);
$ip = $_SERVER['REMOTE_ADDR'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$guestbook = Guest_books::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'web' => $request->input('web'),
'comment' => $request->input('comment'),
'ip' => $ip,
'browser' => $browser
]);
return $guestbook;
}
So the question is: What to write in Controller for project to verify Captcha and then post it to database?
The tutorial you've followed teaches you how to create a custom validation rule which you can then use when validating requests, either through a Form Request or directly in your controller.
The mistake you've made in your controller is that you've called validate multiple times, instead you should pass it an array containing all of your rules, including your recaptcha rule, e.g:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email',
'comment' => 'required',
'g-recaptcha-response' => 'required|recaptcha',
]);
// ...
}
Additionally, you should note that the store method should always return a redirect.

How to insert multiple rows in laravel 5?

I want to insert an array with an id :
create.blade :
{{ Form::open(array('route' => 'Charge.store','method'=>'POST')) }}
<select id="disabledSelect" class="form-control" name="Facture_id">
<option value="{{ $Facture->id }}" >{{ $Facture->Num }}</option>
</select>
<br/>
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Title]" placeholder="libelé"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Quantity]" placeholder="Quantité"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="rows[0][Price]" placeholder="Prix unitaire "/>
</div>
<div class="form-group">
<input type="button" class="btn btn-default" value="Ajouter" onclick="createNew()" />
</div>
<div id="mydiv"></div>
</div>
<br/>
<div class="form-group">
<input type="submit" value="Ajouter" class="btn btn-info">
Cancel
</div>
{{ Form::close() }}
<script>
var i = 2;
function createNew() {
$("#mydiv").append('<div class="form-group">'+'<input type="text" name="rows[' + i +'][Title]" class="form-control" placeholder="libelé"/>'+
'</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Quantity]" class="form-control" placeholder="Quantité"/>'+'</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Price]" class="form-control" placeholder="Prix unitaire "/>'+'</div>'+'<div class="form-group">'+
'<input type="button" name="" class="btn btn-default" value="Ajouter" onclick="createNew()" />'+
'</div><br/>');
i++;
}
</script>
here is my controller , when I tried to submit the form , it inject rows with value of 0.
What should I do ? I tried to use elequent bolk data , but the problem remain the same:
public function store(Request $request)
{
// validated input request
$this->validate($request, [
'Facture_id' => 'required',
]);
// create new task
$rows = $request->input('rows');
foreach ($rows as $row)
{
$Charges[] = new Charge(array(
'course_id'=>$request->input('Facture_id'),
'Title'=>$row['Title'],
'Quantity'=>$row['Quantity'],
'Price'=>$row['Price'],
));
}
Charge::create($Charges);
return redirect()->route('Charge.index')->with('success', 'Your task added successfully!');
}
You can use insert() method:
foreach ($rows as $row)
{
$charges[] = [
'course_id' => $request->input('Facture_id'),
'Title' => $row['Title'],
'Quantity' => $row['Quantity'],
'Price' => $row['Price'],
];
}
Charge::insert($charges);
Don't forget to add all column names you use to a $fillable array:
$fillable = ['course_id', 'Title', 'Quantity', 'Price'];

Resources