production.ERROR: InvalidArgumentException: Data missing in Laravel - laravel

I am working on a project in Laravel-5.8. I have this in my model:
Model:
protected $fillable = [
'id',
'email',
'hire_date',
'first_name',
'other_name',
'last_name',
'date_of_birth',
];
protected $dates = [
'date_of_birth',
'hire_date',
];
public function setDateOfBirthAttribute($value)
{
$this->attributes['date_of_birth'] = Carbon::createFromFormat('d-m-Y', $value);
}
public function setHireDateAttribute($value)
{
$this->attributes['hire_date'] = Carbon::createFromFormat('d-m-Y', $value);
}
Then this is my controller.
Controller:
$arr = [
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'hire_date' => $request->hire_date,
'date_of_birth' => $request->date_of_birth,
'other_name' => $request->other_name,
];
$employee = HrEmployee::create($arr);
I use JQuery datepicker:
< script type = "text/javascript" >
$(function() {
$('.birthDate').datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
maxDate: -1,
showAnim: 'slideDown',
duration: 'fast',
});
}); <
/script>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Date of Birth:</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-calendar-alt"></i></span>
</div>
<input type="text" placeholder="dd/mm/yyyy" readonly autocomplete="off" name="date_of_birth" value="{{ old(" date_of_birth} ") }}" class="form-control birthDate">
</div>
</div>
<!-- /.form-group -->
</div>
When I submitted the form, I got this error:
[2021-02-12 12:50:07] production.ERROR: InvalidArgumentException: Data missing in /var/www/html/peopleedgeapp/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php:623
Stack trace:
#0 /var/www/html/myapp/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php(645): Carbon\Carbon::rawCreateFromFormat('d-m-Y', NULL, NULL)
#1 /var/www/html/myapp/app/Models/Hr/HrEmployee.php(156): Carbon\Carbon::createFromFormat('d-m-Y', NULL)
#2 /var/www/html/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(615): App\Models\Hr\HrEmployee->setDateOfBirthAttribute(NULL)
#3 /var/www/html/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(569): Illuminate\Database\Eloquent\Model->setMutatedAttributeValue('date_of_birth', NULL)
#4 /var/www/html/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(329): Illuminate\Database\Eloquent\Model->setAttribute('date_of_birth', NULL)
Where did I get it wrong? The same error occur for hire_date.
How do I get this resolved?
Thanks

Hard to say what's exactly wrong but for sure there is a problem here:
value="{{ old(" date_of_birth} ") }}"
It should be rather:
value="{{ old('date_of_birth') }}"

First of all set attribute methods are not used for guarded fields.
They have completely different perpouse.
Secondary, according to your error log somehow your setters were triggered with NULL passing instead of parameters, where parameters are required which is also wrong.
So where your setters triggered that is the question I think.

Related

Laravel 9 Vue js 3 multipart form, console showing full html, not only the retrieved data

I'm using a multipart form to send texts and image to database,
The data have been successfully sent to the database, but why in the console it is showing the data infull html ? not only the data that has been retrieved ?
this is my code
<template>
<div class="gabungPage">
<div class="row">
<div class="backgroundGabung" id="hrefGabung">
<div class="tulisanGabung p-5">
<div class="cardGabung">
<p class="teksGabung">Tingkatkan bisnismu sekarang dengan bergabung menjadi mitra JAI'</p>
<form #submit.prevent="submitForm">
<div class="form-group">
<label for="nama">Nama</label>
<input
type="text"
id="nama"
v-model="formulirs.nama"
class="form-control"
/>
</div>
<div class="form-group">
<label for="alamat">Alamat</label>
<input
type="text"
id="alamat"
v-model="formulirs.alamat"
class="form-control"
/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input
type="text"
id="email"
v-model="formulirs.email"
class="form-control"
/>
</div>
<div class="form-group">
<label for="nomor">nomor</label>
<input
type="text"
id="nomor"
v-model="formulirs.nomor"
class="form-control"
/>
</div>
<div class="form-group">
<label for="image">Image</label>
<input
type="file"
id="image"
ref="imageInput"
#change="uploadImage"
/>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<div class="tesss">
<h1> <span class="tulisKiri1">Gabung jadi</span> <br> <span class="tulisKiri2">mitra jahit</span></h1>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
formulirs: {
nama: '',
alamat: '',
nomor: '',
email: '',
image: null,
},
};
},
methods: {
uploadImage() {
this.formulirs.image = this.$refs.imageInput.files[0];
},
async submitForm() {
const formData = new FormData();
formData.append('nama', this.formulirs.nama);
formData.append('alamat', this.formulirs.alamat);
formData.append('email', this.formulirs.email);
formData.append('nomor', this.formulirs.nomor);
formData.append('image', this.formulirs.image);
axios.post('/api/submit-form', formData).then(
response => {
console.log(response);
this.$toast.success(`Data berhasil dikirim`,{
position: "bottom",
});
}
). catch(error => {
console.log('error');
this.$toast.error(`Terjadi kegagalan`,{
position: "bottom",
});
})
},
},
};
</script>
the routes/web.php
Route::post('/api/submit-form', [FormulirsController::class, 'store']);
the controller
public function store(Request $request)
{
$validatedData = $request->validate([
'nama' => 'required',
'alamat' => 'required',
'nomor' => 'required',
'email' => 'required|email',
'image' => 'required|image',
]);
$formulir = new Formulirs;
$formulir->nama = $validatedData['nama'];
$formulir->alamat = $validatedData['alamat'];
$formulir->nomor = $validatedData['nomor'];
$formulir->email = $validatedData['email'];
$image = $request->file('image');
$imageName = time().$image->getClientOriginalName();
$image->storeAs('public/images', $imageName);
$formulir->image = $imageName;
$formulir->save();
return back()->with('success', 'Data berhasil dikirim');
}
I have tried to show the data only by changing to
console.log(response.data)
But it got worse, it only shows full html page in the console, what should I do so that it doesn't display the full html page?
You're making an axios request and returning back method. This is used for redirecting in a monolitic app. I recommend you return a JSON response in your controller. Something like this:
public function store(Request $request)
{
$validatedData = $request->validate([
'nama' => 'required',
'alamat' => 'required',
'nomor' => 'required',
'email' => 'required|email',
'image' => 'required|image',
]);
$formulir = new Formulirs;
$formulir->nama = $validatedData['nama'];
$formulir->alamat = $validatedData['alamat'];
$formulir->nomor = $validatedData['nomor'];
$formulir->email = $validatedData['email'];
$image = $request->file('image');
$imageName = time().$image->getClientOriginalName();
$image->storeAs('public/images', $imageName);
$formulir->image = $imageName;
$formulir->save();
return back()->with('success', 'Data berhasil dikirim'); // this is yours
return response()->json('Data berhasil dikirim'); // 200 status code is the second param by default. You can change for whatever you want.
}

How to add Recaptcha v2 to Laravel and Vue js?

I'm following this article on how to add Recaptcha v2 to a Laravel and Vue js project.
https://www.itechempires.com/2018/05/how-to-implement-google-recapcha-with-vuejs-and-laravel-5-6/
I'm trying to implement it in my project but I'm getting this error on the page:
The recaptcha verification failed. Try again.
And in the network tab this error:
{recaptcha: ["The recaptcha verification failed. Try again."]}
And in the console:
POST http://highrjobsadminlte.test/submit 422 (Unprocessable Entity)
I'm trying to implement this on a Contact Form on my Contact.vue page.
Contact.vue:
<form #submit.prevent="submit">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" v-model="fields.name" />
<div v-if="errors && errors.name" class="text-danger" style="font-size: 13px;">{{ errors.name[0] }}</div>
</div>
<div class="form-group">
<label for="email">E-mail</label>
<input type="email" class="form-control" name="email" id="email" v-model="fields.email" />
<div v-if="errors && errors.email" class="text-danger" style="font-size: 13px;">{{ errors.email[0] }}</div>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message" name="message" rows="5" v-model="fields.message"></textarea>
<div v-if="errors && errors.message" class="text-danger" style="font-size: 13px;">{{ errors.message[0] }}</div>
</div>
<div class="form-group">
<vue-recaptcha
v-model="fields.recaptcha"
ref="recaptcha"
#verify="onVerify"
sitekey="6LcAHcoZAAAAAFDOejn9e2LrogSpF41RMlXtrpDa">
</vue-recaptcha>
</div>
<div v-if="errors && errors.recaptcha" class="text-danger" style="font-size: 13px;">{{ errors.recaptcha[0] }}</div>
<button type="submit" class="btn btn-primary mt-3">Send message</button>
</form>
export default {
name: "Contact",
data() {
return {
fields: {},
errors: {},
}
},
methods: {
onVerify(response) {
this.fields.recaptcha = response;
},
submit() {
this.errors = {};
axios.post('/submit', this.fields, {
headers:{
'Content-Type':'application/json',
'Accept':'application/json'
}
}).then(({data: {fields}}) => {
this.$toast.success('Message sent successfully!');
this.$refs.recaptcha.reset();
}).catch(error => {
if (error) {
this.errors = error.response.data.errors || {};
}
});
},
},
}
Recaptcha.php (This is a rule):
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Zttp\Zttp;
class Recaptcha implements Rule
{
const URL = 'https://www.google.com/recaptcha/api/siteverify';
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
return Zttp::asFormParams()->post(static::URL, [
'secret' => config('services.recaptcha.secret'),
'response' => $value,
'remoteip' => request()->ip()
])->json()['success'];
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The recaptcha verification failed. Try again.';
}
/**
* Determine if Recaptcha's keys are set to test mode.
*
* #return bool
*/
public static function isInTestMode()
{
return Zttp::asFormParams()->post(static::URL, [
'secret' => config('services.recaptcha.secret'),
'response' => 'test',
'remoteip' => request()->ip()
])->json()['success'];
}
}
ContactFormController.php:
<?php
namespace App\Http\Controllers;
use App\Mail\ContactEmail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Rules\Recaptcha;
class ContactFormController extends Controller
{
public function submit(Request $request, Recaptcha $recaptcha) {
$this->validate($request, [
'name' => 'required|string',
'email' => 'required|email',
'message' => 'required',
'recaptcha' => ['required', $recaptcha],
]);
$contact = [];
$contact['name'] = $request->get('name');
$contact['email'] = $request->get('email');
$contact['subject'] = $request->get('subject');
$contact['message'] = $request->get('message');
// Mail Delivery logic goes here
Mail::to(config('mail.from.address'))->send(new ContactEmail($contact));
return response(['contact' => $contact], 200);
}
}
web.php:
Route::post('/submit', 'ContactFormController#submit');
And I have set recaptcha key and secret in config/services.php to point to my .env variables which are set in my .env file.

How to display validation errors?

Router
Route::get('/contact',['uses'=>'Admin\ContactController#show','as'=>'contact']);
Route::post('/contact',['uses'=>'Admin\ContactController#store']);
Controller
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\ContactRequest;
use App\Http\Controllers\Controller;
use Validator;
class ContactController extends Controller
{
public function store(Request $request,$id=FALSE) {
if($request->isMethod('post')) {
$messages = [
'name.required' => 'ПОЛЕ :attribute обязательно к заполнению!!!!',
'email.max' => 'Максимально допустимое количество символов - :max',
];
$validator = Validator::make($request->all(),[
'name'=>'required',
/*'email'=>'required'*/
],$messages);
$validator->sometimes(['email','site'],'required',function($input) {
/*dump($input);
exit();*/
return strlen($input->name) >= 10;
});
$validator->after(function($validator) {
$validator->errors()->add('name','ДОполнительное сообщение');
});
if($validator->fails()) {
$messages = $validator->errors();
//dump ($messages->first());
dump($validator->failed());
exit();
return redirect()->route('contact')->withErrors($validator)->withInput();
}
}
return view('default.contact',['title'=>'Contacts']);
}
public function show() {
return view('default.contact',['title'=>'Contacts']);
}
}
Template
extends('default.layouts.layout')
#section('content')
<div class="col-md-9">
<div class="">
<h2>Contact us!</h2>
</div>
<p>
This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.
</p>
{{ count($errors)}}
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error}}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ route('contact') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}" placeholder="Jane Doe">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" value="{{ old('email') }}" name="email" placeholder="Email">
</div>
<div class="form-group">
<label for="site">Site</label>
<input type="text" class="form-control" id="site" value="{{ old('site') }}" name="site" placeholder="Site">
</div>
<div class="form-group">
<label for="text">Text</label>
<textarea class="form-control" id="text" name="text" rows="3">{{ old('text') }}</textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
#endsection
The problem is that I have not displayed validation error and the message "further message". Although the validation is successful. The problem is. I don't want to display $messages I tried to walk on it with foreach, but laravel says that it found the $messages. Although the controller $messages displayed. The pattern also shows that the errors I have 0, but in the controller I have shows validation errors.
What's the problem?
try this:i hope it will work for you.
//controller
if ($request->method() == 'POST') {
$rules = [
'name' => 'required',
'email' => 'required'
];
$validator = Validator::make($request->all(), $rules);
if (!$validator->fails()) {
}
else{
//validation_error();
}
}
and use js for validation
$(function () {
$("#form_id").validate({
errorElement: 'small', errorClass: 'invalid-feedback',
rules: {
name: {
required: true,
},
email: {
required: true,
}
},
messages: {
name: {
required: "Name Field Is Required.",
},
email: {
required: "Email Field Is Required.",
}
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
success: function (element) {
$(element).closest('.form-group').removeClass('has-error');
$(element).closest('.form-group').children('small.invalid-feedback').remove();
},
errorPlacement: function (error, element) {
error.appendTo(element.closest('.form-group'));
},
submitHandler: function (form) {
$(window).block({
'message': '<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>',
'css': {
border: '0',
padding: '0',
backgroundColor: 'none',
marginTop: '5%',
zIndex: '10600'
},
overlayCSS: {backgroundColor: '#555', opacity: 0.3, cursor: 'wait', zIndex: '10600'},
});
$.post('', $("#form_id").serialize(), function (data) {
if (data.code == '1') {
swal({
title: "",
text: data.message,
type: "success"
}, function () {
document.location.href = base_url + '/listing_page';
});
} else if (data === '0') {
swal("", "Something wrong while save building information.", "warning");
} else {
swal("", data, "error");
}
$(window).unblock();
});
}
});
$('select').change(function () {
$("#form_id").validate().element($(this));
});
});

Call to a member function getClientOriginalName() on null when upload image use file system Laravel

I want to upload an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image.
Call to a member function getClientOriginalName() on null
Controller
public function store(Request $request)
{
$admin = $request->all();
$fileName = $request->file('foto')->getClientOriginalName();
$destinationPath = 'images/';
$proses = $request->file('foto')->move($destinationPath, $fileName);
if($request->hasFile('foto'))
{
$obj = array (
'foto' => $fileName,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
}
return redirect()->route('admin-index');
}
View
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
Error
You can check wheather you are getting file or not by var_dump($request->file('foto')->getClientOriginalName());
And make sure your form has enctype="multipart/form-data" set
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
Error because of client Side
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
you ned to add enctype="multipart/form-data" inside the form
If You are using the form builder version
{!! Form::open(['url' => ['store'],'autocomplete' => 'off','files' => 'true','enctype'=>'multipart/form-data' ]) !!}
{!! Form::close() !!}
Then In your Controller You can check if the request has the file
I have Created the simple handy function to upload the file
Open Your Controller And Paste the code below
private function uploadFile($fileName = '', $destinationPath = '')
{
$fileOriginalName = $fileName->getClientOriginalName();
$timeStringFile = md5(time() . mt_rand(1, 10)) . $fileOriginalName;
$fileName->move($destinationPath, $timeStringFile);
return $timeStringFile;
}
And the store method
Eloquent way
public function store(Request $request)
{
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile= $this->uploadFile($request->foto,$destinationPath );
}
Admin::create(array_merge($request->all() , ['foto' => $fotoFile]));
return redirect()->route('admin-index')->with('success','Admin Created Successfully');
}
DB Facade Version
if You are using DB use use Illuminate\Support\Facades\DB; in top of your Controller
public function store(Request $request)
{
$admin = $request->all();
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile = $this->uploadFile($request->foto,$destinationPath );
}
$obj = array (
'foto' => $fotoFile,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
return redirect()->route('admin-index');
}
Hope it is clear

codeigniter login validation not validating rules

am using codeigniter 3.0.4 .here this Here the action send to the controler(first.php)not validating anything it will turn to else statement and display login page again(as set as in redirect('welcome/login_page');). my register function in the same controller working good. what is the exact problem ..please help me to find it.thanks.
..............the controller(first.php).....
public function signup_validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|valid_email|callback_validate_credentials');
$this->form_validation->set_rules('password', 'Password', 'required|md5|trim');
if($this->form_validation->run() ){
$user_id= $this->model_users->get_id($this->input->post('email'));
$user_status = $this->model_users->get_status($this->input->post('email'));
$data = array (
'user_id' => $user_id,
'email' => $this->input->post('email'),
'user_status' =>$user_status,
'is_logged_in' => 1
);
$this->session->set_userdata($data);
}
if ($this->session->userdata('user_status')=='0') {
redirect('main/admins');
}
elseif ($this->session->userdata('user_status')=='1') {
redirect('main/members');
}else{
redirect('welcome/login_page');
}
}
public function validate_credentials(){
$this->load->model('model_users');
if($this->model_users->can_log_in() ){
return TRUE;
} else {
$this->form_validation->set_message('validate_credentials', 'Invalid useername(email-id) or password. !');
return FALSE;
}
}
....the view(login.php)......
echo form_open("first/signup_validation");
echo'<div class="row">';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="email">Email<span></span></label>';
echo'<input type="text" class="form-control" id="email">';
echo'</div>';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="password">Password<span></span></label>';
echo'<input type="password" class="form-control" id="password">';
echo'</div>';
echo'</div>';
$data2 = array(
'class' => 'btn btn-default',
);
echo form_submit($data2, 'Login');
echo form_close('');
?>
echo '<input type="text" class="form-control" id="email">';
Your input elements don't contain a name attribute. The name is what's used as the identifier in the validation rule.
$this->form_validation->set_rules('email'... // <- 'email' is the name attribute
Do this...
echo'<input type="text" class="form-control" id="email" name="email">';

Resources