Laravel - Some fields save null to the database in my Laravel Project - laravel

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

Related

Laravel 9 uploading to storage and using image for new blog post

Blog post
Above is my blog post, Below I will post my current set up.
New blog form
I'm new to this so, I want to be able to upload images and each of my blog post to pull the requested images. Currently the file selector isn't linked so it creates a fake path.
This is my blogs controller
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Http\Requests\BlogsUpdateRequest;
use App\Http\Requests\DatatablesRequest;
use App\Modules\Blogs\BlogsService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
class BlogsController extends Controller
{
public function __construct(
private readonly BlogsService $service
)
{
}
public function index(DatatablesRequest $request): JsonResponse
{
try {
return response()->json($this->service->index($request->data()));
} catch (Exception $error) {
return response()->json(
[
"exception" => get_class($error),
"errors" => $error->getMessage()
],
Response::HTTP_BAD_REQUEST
);
}
}
public function get(int $id): JsonResponse
{
try {
return response()->json($this->service->get($id));
} catch (Exception $error) {
return response()->json(
[
"exception" => get_class($error),
"errors" => $error->getMessage()
],
Response::HTTP_BAD_REQUEST
);
}
}
public function update(BlogsUpdateRequest $request): JsonResponse
{
try {
return response()->json($this->service->update($request));
} catch (Exception $error) {
return response()->json(
[
"exception" => get_class($error),
"errors" => $error->getMessage()
],
Response::HTTP_BAD_REQUEST
);
}
}
public function delete(int $id): JsonResponse
{
try {
$this->service->delete($id);
return response()->json(null, Response::HTTP_NO_CONTENT);
} catch (Exception $error) {
return response()->json(
[
"exception" => get_class($error),
"errors" => $error->getMessage()
],
Response::HTTP_BAD_REQUEST
);
}
}
}
This is my blogsupdaterequest
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BlogsUpdateRequest extends FormRequest
{
public function rules(): array
{
return [
"id" => "nullable|numeric",
"is_trending" => "required|boolean",
"author" => "required|string",
"author_image_url" => "required|string",
"image_url_portrait" => "required|string",
"image_url_landscape" => "required|string",
"date" => "required|string",
"title" => "required|string",
"tags" => "required|string",
"description" => "required|string",
"content" => "required|string",
];
}
public function data(): array
{
$id = $this->input("id", null);
return [
"id" => ($id === null) ? null : (int)$id,
"is_trending" => $this->input("is_trending", 0),
"author" => $this->input("author"),
"author_image_url" => $this->input("author_image_url"),
"image_url_portrait" => $this->input("image_url_portrait"),
"image_url_landscape" => $this->input("image_url_landscape"),
"date" => $this->input("date"),
"url" => $this->generateUrl($this->input("title")),
"title" => $this->input("title"),
"tags" => array_map(function($row) {
return trim($row);
}, explode(",", $this->input("tags", []))),
"description" => $this->input("description"),
"content" => $this->input("content"),
];
}
private function generateUrl(string $title): string {
$newUrl = trim(strtolower($title));
$newUrl = str_replace(" ", " ", $newUrl);
$newUrl = str_replace(" ", "-", $newUrl);
return preg_replace("/[^A-Za-z0-9\-]/", "", $newUrl);
}
}
Blogs model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Blogs extends Model
{
protected $table = "blogs";
protected $fillable = [
"id",
"is_trending",
"author",
"author_image_url",
"image_url_portrait",
"image_url_landscape",
"title",
"date",
"description",
"content",
"created_at",
"updated_at",
];
public function tags (){
return $this->hasMany(BlogTags::class);
}
}
Blogs.blade
<div class="col-lg-8 col-12">
#foreach($blogs as $blog)
<span onclick="redirectto('{{$blog['url']}}')">
<div class="row mt-4 mb-4 blog-card border rounded">
<div class="col-lg-4 col-12 p-0 m-0">
<img src="{{$blog ['img_url_portrait']}}" alt="" class="rounded w-100 h-100">
</div>
<div class="col-lg-8 col-12 p-lg-5">
<div class="row h-100 pt-4 align-item-center">
<div class="col-12 mx-auto">
<small class="text-muted fs-8">
{{$blog ['date']}}
</small>
<br>
#foreach ($blog['tags'] as $tag)
<span class="text-primary fw-bolder fs-6 pe-1">{{$tag['$tag']}}</span>
#if($loop->iteration < count($blog['tags'])))
<span class="text-primary fw-bolder fs-6 pe-1">•</span>
#endif
#endforeach
<h2 class="fw-lighter fs-2">{{$blog['title'] }}</h2>
<p class="text-muted">{{$blog['description'] }}</p>
<p>
<img src="{{$blog['author_image_url']}}" alt="author image" class="rounded-circle" height="35" width="35">
<span class="ps-1">{{$blog['author']}}</span>
</p>
</div>
</div>
</div>
</div>
</span>
#endforeach
</div>
Images model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Images extends Model
{
protected $table = "image";
protected $fillable = [
"id",
"name",
"location",
"created_at",
"updated_at",
];
}
Form.blade
<div class="modal fade" id="BlogsModal">
<div class="modal-dialog modal-fullscreen text-dark">
<div class="modal-content">
<div class="modal-content container" style="overflow-y:scroll;">
<div class="row">
<div class="col-12 text-end">
<span type="button" class="btn-close" data-bs-dismiss="modal"></span>
</div>
<div class="col-12">
<div id="BlogsErrorsContainer" class="alert alert-danger errorContainer" style="display:none;">
<h5 class="font-weight-bolder">Error!</h5>
<ul></ul>
</div>
</div>
<div class="col-12">
<hr>
<h5 class="modal-title font-weight-bolder">New Blog</h5>
<hr>
<form id="BlogsForm">
<input type="hidden" class="form-control" id="itemId">
<div class="row">
<div class="col-12 mb-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="blogsIsTrending">
<label class="form-check-label">Trending</label>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Title</label>
<input type="text" class="form-control" id="blogsTitle">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Date</label>
<input type="text" class="form-control" id="blogsDate">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Author Name</label>
<input type="text" class="form-control" id="blogsAuthorName">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Author Image URL</label>
<input type="file" class="form-control" id="blogsAuthorImageUrl">
</div>
<div class="col-12">
<hr>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Image Url Landscape</label>
<input type="file" class="form-control" id="blogsImageUrlLandscape">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Image Url Portrait</label>
<input type="file" class="form-control" id="images[]">
</div>
<div class="col-12">
<hr>
</div>
<div class="col-12">
<label class="form-label font-weight-bolder">Tags</label>
<input type="text" class="form-control" id="blogsTags">
<div class="form-text">Tags must be seperated by a comma. Example: <i>Laravel, Hosting</i></div>
</div>
<div class="col-12">
<hr>
</div>
<div class="col-12">
<label class="form-label font-weight-bolder">Description</label>
<textarea rows="2" type="text" class="form-control" id="blogsDescription"></textarea>
<div class="form-text">1-3 sentences max.</div>
</div>
<div class="col-12 mb-5">
<label class="form-label font-weight-bolder">Content</label>
<div id="blogsContent"></div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer container">
<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
<button id="SubmitBlogsForm" type="button" class="btn btn-sm btn-primary">Save Changes</button>
</div>
</div>
</div>
</div>
<script src="//cdn.quilljs.com/1.3.6/quill.min.js"></script>
<script>
let formSubmitted = false;
let blogsEndpoint = "/api/dashboard/blogs";
let quillToolbar = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{
'header': 1
}, {
'header': 2
}], // custom button values
[{
'list': 'ordered'
}, {
'list': 'bullet'
}],
[{
'script': 'sub'
}, {
'script': 'super'
}], // superscript/subscript
[{
'indent': '-1'
}, {
'indent': '+1'
}], // outdent/indent
[{
'direction': 'rtl'
}], // text direction
[{
'size': ['small', false, 'large', 'huge']
}], // custom dropdown
[{
'header': [1, 2, 3, 4, 5, 6, false]
}],
[{
'color': []
}, {
'background': []
}], // dropdown with defaults from theme
[{
'font': []
}],
[{
'align': []
}],
['clean'] // remove formatting button
];
let quill = new Quill(
"#blogsContent", {
modules: {
toolbar: quillToolbar
},
placeholder: "Compose an epic ...",
theme: "snow"
}
);
function clearForm() {
$("#itemId").val(null);
$("#blogsTitle").val(null);
$("#blogsAuthorName").val(null),
$("#blogsAuthorImageUrl").val(null);
$("#blogsImageUrlLandscape").val(null);
$("#blogsImageUrlPortrait").val(null);
$("#blogsTags").val(null);
$("#blogsDescription").val(null);
$("#blogsDate").val(null);
$("#blogsIsTrending").prop("checked", false);
$("#blogsContent").val(null);
quill.setContents([{
insert: "\n"
}]);
clearErrors();
}
function clearErrors() {
$("#BlogsErrorsContainer ul").empty();
$("#BlogsErrorsContainer").hide();
}
function showErrors(errorsList = []) {
Object.keys(errorsList).forEach(key => {
$("#BlogsModal .errorContainer ul").append(
"<li><b>" + key + ": </b>" + errorsList[key] + "</li>"
);
$("#BlogsModal .errorContainer").show();
});
}
$(document).ready(function() {
$("#SubmitBlogsForm").click(function() {
event.preventDefault();
clearErrors();
if (formSubmitted !== true) {
formSubmitted = true;
$.ajax({
type: "POST",
url: blogsEndpoint,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
id: $("#itemId").val(),
title: $("#blogsTitle").val(),
author: $("#blogsAuthorName").val(),
author_image_url: $("#blogsAuthorImageUrl").val(),
image_url_landscape: $("#blogsImageUrlLandscape").val(),
image_url_portrait: $("#blogsImageUrlPortrait").val(),
tags: $("#blogsTags").val(),
description: $("#blogsDescription").val(),
date: $("#blogsDate").val(),
is_trending: $("#blogsIsTrending").prop("checked"),
content: quill.root.innerHTML.trim(),
}),
success: function(response) {
formSubmitted = false;
$BlogsModal.hide();
$("#dataTable").DataTable().ajax.reload();
}
}).fail(function(response) {
formSubmitted = false;
if (response.status === 422) {
showErrors(response.responseJSON["errors"]);
} else {
showErrors({
Error: "Could not process your request! Please try again later."
});
}
});
}
});
});
</script><div class="modal fade" id="BlogsModal">
<div class="modal-dialog modal-fullscreen text-dark">
<div class="modal-content">
<div class="modal-content container" style="overflow-y:scroll;">
<div class="row">
<div class="col-12 text-end">
<span type="button" class="btn-close" data-bs-dismiss="modal"></span>
</div>
<div class="col-12">
<div id="BlogsErrorsContainer" class="alert alert-danger errorContainer" style="display:none;">
<h5 class="font-weight-bolder">Error!</h5>
<ul></ul>
</div>
</div>
<div class="col-12">
<hr>
<h5 class="modal-title font-weight-bolder">New Blog</h5>
<hr>
<form id="BlogsForm">
<input type="hidden" class="form-control" id="itemId">
<div class="row">
<div class="col-12 mb-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="blogsIsTrending">
<label class="form-check-label">Trending</label>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Title</label>
<input type="text" class="form-control" id="blogsTitle">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Date</label>
<input type="text" class="form-control" id="blogsDate">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Author Name</label>
<input type="text" class="form-control" id="blogsAuthorName">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Author Image URL</label>
<input type="text" class="form-control" id="blogsAuthorImageUrl">
</div>
<div class="col-12">
<hr>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Image Url Landscape</label>
<input type="text" class="form-control" id="blogsImageUrlLandscape">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Image Url Portrait</label>
<input type="text" class="form-control" id="blogsImageUrlPortrait">
</div>
<div class="col-12">
<hr>
</div>
<div class="col-12">
<label class="form-label font-weight-bolder">Tags</label>
<input type="text" class="form-control" id="blogsTags">
<div class="form-text">Tags must be seperated by a comma. Example: <i>Laravel, Hosting</i></div>
</div>
<div class="col-12">
<hr>
</div>
<div class="col-12">
<label class="form-label font-weight-bolder">Description</label>
<textarea rows="2" type="text" class="form-control" id="blogsDescription"></textarea>
<div class="form-text">1-3 sentences max.</div>
</div>
<div class="col-12 mb-5">
<label class="form-label font-weight-bolder">Content</label>
<div id="blogsContent"></div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer container">
<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
<button id="SubmitBlogsForm" type="button" class="btn btn-sm btn-primary">Save Changes</button>
</div>
</div>
</div>
</div>
<script src="//cdn.quilljs.com/1.3.6/quill.min.js"></script>
<script>
let formSubmitted = false;
let blogsEndpoint = "/api/dashboard/blogs";
let quillToolbar = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{
'header': 1
}, {
'header': 2
}], // custom button values
[{
'list': 'ordered'
}, {
'list': 'bullet'
}],
[{
'script': 'sub'
}, {
'script': 'super'
}], // superscript/subscript
[{
'indent': '-1'
}, {
'indent': '+1'
}], // outdent/indent
[{
'direction': 'rtl'
}], // text direction
[{
'size': ['small', false, 'large', 'huge']
}], // custom dropdown
[{
'header': [1, 2, 3, 4, 5, 6, false]
}],
[{
'color': []
}, {
'background': []
}], // dropdown with defaults from theme
[{
'font': []
}],
[{
'align': []
}],
['clean'] // remove formatting button
];
let quill = new Quill(
"#blogsContent", {
modules: {
toolbar: quillToolbar
},
placeholder: "Compose an epic ...",
theme: "snow"
}
);
function clearForm() {
$("#itemId").val(null);
$("#blogsTitle").val(null);
$("#blogsAuthorName").val(null),
$("#blogsAuthorImageUrl").val(null);
$("#blogsImageUrlLandscape").val(null);
$("#blogsImageUrlPortrait").val(null);
$("#blogsTags").val(null);
$("#blogsDescription").val(null);
$("#blogsDate").val(null);
$("#blogsIsTrending").prop("checked", false);
$("#blogsContent").val(null);
quill.setContents([{
insert: "\n"
}]);
clearErrors();
}
function clearErrors() {
$("#BlogsErrorsContainer ul").empty();
$("#BlogsErrorsContainer").hide();
}
function showErrors(errorsList = []) {
Object.keys(errorsList).forEach(key => {
$("#BlogsModal .errorContainer ul").append(
"<li><b>" + key + ": </b>" + errorsList[key] + "</li>"
);
$("#BlogsModal .errorContainer").show();
});
}
$(document).ready(function() {
$("#SubmitBlogsForm").click(function() {
event.preventDefault();
clearErrors();
if (formSubmitted !== true) {
formSubmitted = true;
$.ajax({
type: "POST",
url: blogsEndpoint,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
id: $("#itemId").val(),
title: $("#blogsTitle").val(),
author: $("#blogsAuthorName").val(),
author_image_url: $("#blogsAuthorImageUrl").val(),
image_url_landscape: $("#blogsImageUrlLandscape").val(),
image_url_portrait: $("#blogsImageUrlPortrait").val(),
tags: $("#blogsTags").val(),
description: $("#blogsDescription").val(),
date: $("#blogsDate").val(),
is_trending: $("#blogsIsTrending").prop("checked"),
content: quill.root.innerHTML.trim(),
}),
success: function(response) {
formSubmitted = false;
$BlogsModal.hide();
$("#dataTable").DataTable().ajax.reload();
}
}).fail(function(response) {
formSubmitted = false;
if (response.status === 422) {
showErrors(response.responseJSON["errors"]);
} else {
showErrors({
Error: "Could not process your request! Please try again later."
});
}
});
}
});
});
</script>

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

Array to String conversion error while trying to do a single file upload in Laraver using AJAX

I'm having form which submits one file and certain texts through AJAX, only problem is with the file upload through AJAX. The form dats is being submitted through FormData instance but getting an Array to String conversion error while trying to save the file.
I'm attaching the scripts below.
Controller:
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'contact_number' => 'required|numeric',
'email' => 'required',
'total_exp' => 'required|numeric',
'skillsets' => 'required',
'current_organization' => '',
'remarks' => '',
'file_name' => 'required|max:2048'
],
[
'name' => 'This field is mandatory',
'contact_number' => 'This field is mandatory',
'email' => 'This field is mandatory',
'total_exp' => 'This field is mandatory',
'skillsets' => 'This field is mandatory',
'total_exp.numeric' => 'Only numberic values allowed',
'contact_number.numeric' => 'Only numberic values allowed'
]);
//try{
$career = CareerForm::updateOrCreate([
'name'=>$request->name,
'contact_number'=>$request->contact_number,
'email'=>$request->email,
'total_exp'=>$request->total_exp,
'skillsets'=>$request->skillsets,
'current_organization'=>$request->current_organization,
'remarks'=>$request->remarks,
'file_name' => $request->file_name,
]);
//if(request()->hasFile('file_name')){
$file=$request->file('file_name');
$fname = rand().'.'.$file('file_name')->getClientOriginalName().'.'.$file('file_name')->getClientOriginalExtension();
$file->move(public_path('documents'),$fname);
//$file->move(public_path('uploads'), $fname);
//$request->file->move(public_path('uploads'), $fileName);*/
/*$file = $request->file('file_name')->store('public/documents');
Storage::disk('local')->put($request->file($request->file)->getClientOriginalName(), 'Contents');*/
//}catch(Exception $e1){echo $e1;}
return response()->json([
"success" => true,
]);
View:
#extends('layouts.app')
#section('content')
<h2>Career Form using AJAX</h2>
<form class="form-signin" id="form_todo" enctype="multipart/form-data">
<h1 class="h3 mb-3 font-weight-normal">Career Form</h1>
<label for="inputEmail" class="sr-only">Name</label>
<input name="name" type="text" id="inputName" class="form-control" placeholder="Name" required="" autofocus="">
#error('name')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Contact Number</label>
<input name="contact_number" type="" id="c_n" class="form-control" placeholder="Contact Number" required="" autofocus="">
#error('contact_number')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Email</label>
<input name="email" type="text" id="eml" class="form-control" placeholder="Email" required="" autofocus="">
#error('email')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Total Experience</label>
<input name="total_exp" type="" id="exp" class="form-control" placeholder="Total Experience" required="" autofocus="">
#error('total_experience')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Skillsets</label>
<input name="skillsets" type="text" id="skl" class="form-control" placeholder="Skillsets" required="" autofocus="">
#error('skillsets')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Curent Organization</label>
<input name="current_organization" type="text" id="c_o" class="form-control" placeholder="Current Organizations (Optional)" autofocus="">
#error('current_organization')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Remarks</label>
<input name="remarks" type="text" id="rem" class="form-control" placeholder="Remarks (Optional)" autofocus="">
#error('remarks')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<input type="file" id="file_id" name="file_name[]" class="form-control">
<!--<button type="button" id="btnFile" class="btn btn-primary">Submit File</button>-->
<button class="btn btn-primary btn-block" id="career_btn" type="submit">Submit</button>
</form>
<p class="mt-5 mb-3 text-muted">Done by Debajyoti Das</p>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
$("#form_todo").on('submit',function(e) {
//$("#career_btn").click(function(e) {
e.preventDefault();
//var formData = new FormData($(this)[0]);
//var files = $("#file_id")[0].files;
var formData = new FormData(this);
//formData.append('file_id',files[0]);
$.ajax({
type: 'POST',
url: "career/store",
data: formData,
datatype: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function(data) {
}
});
});
</script>
#endsection
JSON error message: Array to string conversion
Any help will be appreciated.
On your server You have accepted an array of files.
$files=$request->file('file_name');
foreach ($files as file) {
$fname = rand().'.'.$file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
$file->move(public_path('documents'),$fname);
}

AJAX response issue in modal

I have an AJAX request to add form fields in a database, but got issues while appending the new entry in my select list.
Here's the HTML
<select id="jform_proprietaire" name="jform[proprietaire]">
<option value="8">Hello World</option>
<option value="35">Jon Jon</option>
<option value="9">Jack Jonhson</option>
</select>
The Form in modal :
<div id="myModal" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" style="display: block;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Ajouter un proprietaire</h3>
</div>
<div class="modal-body">
<form method="post" name="adminForm" id="propritaire-form">
<fieldset class="adminform">
<div class="resultats"></div>
<div class="control-group">
<div class="control-label"><label id="nom-lbl" for="nom" aria-invalid="false">
Nom</label>
</div>
<div class="controls"><input type="text" name="nom" id="nom" value=""></div>
</div>
<div class="control-group">
<div class="control-label"><label id="prenom-lbl" for="prenom" aria-invalid="false">
Prénom</label>
</div>
<div class="controls"><input type="text" name="prenom" id="prenom" value=""></div>
</div>
<div class="control-group">
<div class="control-label"><label id="societe-lbl" for="societe" aria-invalid="false">
Société</label>
</div>
<div class="controls"><input type="text" name="societe" id="societe" value=""></div>
<div class="control-group">
<div class="control-label"><label id="email-lbl" for="email" aria-invalid="false">
Email</label>
</div>
<div class="controls"><input type="email" name="email" class="validate-email" id="email" value=""></div>
</div>
</fieldset>
<input type="hidden" name="6f179ffa2a28133151f3cfe1553978e3" value="1">
</form>
</div>
<div class="modal-footer">
<a id="enregistrerproprio" class="btn btn-primary">Enregistrer</a>
</div>
</div>
And the script :
jQuery(document).ready(function(){
jQuery('#myModal').on('shown', function () {
jQuery('#enregistrerproprio').click(function(){
form=jQuery('#propritaire-form')
jQuery('#propritaire-form .resultats').html('<div class=\"progress progress-striped\"><div class=\"bar\" style=\"width: 30%;\"></div></div>');
jQuery.ajax({
type: 'POST',
url: 'index.php?option=com_visites&task=ajax.ajouteProprietaire&format=raw',
data: form.serializeArray(),
dataType: 'json',
success: function(data) {
jQuery('#propritaire-form .resultats').empty();
if(data.succes==1){
jQuery('#myModal').modal('hide');
jQuery('#jform_proprietaire').append('<option selected=\"true\" value=\"'+data.proprietaire.id+'\">'+data.proprietaire.nom+' '+data.proprietaire.prenom+'</option>');
} else {
jQuery('#propritaire-form .resultats').html('<div class=\"alert alert-error\"></div>');
for (i=0;i<data.retour.length;i++){
jQuery('#propritaire-form .resultats .alert').append('<p>'+data.retour[i].message+'</p>')
}
}
}
});
})
})
})
My data is well imported to the database but I have in console :
Uncaught TypeError: Cannot read property 'id' of null
at Object.success (index.php?option=com_jea&view=property&layout=edit&id=344:60)
at i (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:2)
at Object.fireWith [as resolveWith] (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:2)
at y (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:4)
at XMLHttpRequest.c (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:4)
For this line :
jQuery('#jform_proprietaire').append('<option selected=\"true\" value=\"'+data.proprietaire.id+'\">'+data.proprietaire.nom+' '+data.proprietaire.prenom+'</option>');
If someone could help would be great!!
Thanks in advance !
PS : I ommited to show the php ajouteproprietairefunction :
class VisitesControllerAjax extends JControllerAdmin
{
public function ajouteProprietaire(){
require_once JPATH_ADMINISTRATOR.'/components/com_visites/models/propritaire.php';
$input = JFactory::getApplication()->input;
$data=$input->getArray(array('nom' => '', 'prenom' => '', 'societe' => '','email' => '', 'telephone' => '', 'mobile' => '','adresse' => '', 'codepostal' => '', 'ville' => '', 'notes' => ''));
$data["state"]=1;
$model=new VisitesModelPropritaire();
$reussite=$model->save($data);
if ($reussite) {
$db= JFactory::getDbo();
$query=$db->getQuery(true);
$query->select('*')
->from('#__visites_proprio')
->where('id='.$db->insertid());
$db->setQuery($query);
$proprietaire=$db->loadObject();
echo json_encode(array('succes'=>1, 'proprietaire'=>$proprietaire));
} else {
echo json_encode(array('succes'=>0, 'retour'=>JFactory::getApplication()->getMessageQueue()));
}
}
}
Ok found the solution....
In the latest version of MySql the Last Insert ID isn't working very well.
So I changed my function to check on the email field since It's Unique for each user, Here's the updated code :
if ($reussite) {
$db= JFactory::getDbo();
$query=$db->getQuery(true);
$query->select('*');
$query->from('#__visites_proprio');
$query->where('email = \''.$data['email'].'\'');
$db->setQuery($query);
$proprietaire=$db->loadObject();
echo json_encode(array('succes'=>1, 'proprietaire'=>$proprietaire));
} else {
echo json_encode(array('succes'=>0, 'retour'=>JFactory::getApplication()->getMessageQueue()));
}

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