keep getting an error while saving data into database in laravel - php

I am using laravel ver "laravel/framework": "5.8.*"
I want to save the data into database with post request and my post data is
I have searched on this many topics but I can't get any information on this specific topic. If anyone can, it will be very helpful to me.
I saw my previous codes they this type of code in laravel but they work fine why this is not saving and getting an error.
{
"userID": 11,
"fullname": "dharmendra shah",
"fatherName": "manohar shah",
"Mothername": "manorama devi",
"dobdate": "21",
"dobmonth": "August",
"dobYear": "1999",
"caste": "OBC",
"casteCertificateIs": "state",
"emailAddress": "dharmonly1999#gmail.com",
"gender": "Male",
"handiCappedStatus": "Not handicapped",
"nationality": "india",
"state": "Rajasthan",
"district": "bikaner",
"tahsil": null,
"village": "NA",
"maritalStatus": "UnMarried",
"spouseName": null,
"children": null
}
In laravel route my controller is :
public function store(Request $request)
{
$this->validate($request, [
'fullname' => 'required|max:25',
'fatherName' => 'required|max:25',
'Mothername' => 'required|max:25',
'dobdate' => 'required',
'dobmonth' => 'required',
'dobmonth' => 'required',
'dobYear' => 'required',
'caste' => 'required',
'casteCertificateIs'=>'required',
'emailAddress' => 'required|email',
'gender' => 'required',
'handiCappedStatus' => 'required',
'nationality' => 'required',
'state' => 'required',
'district' => 'required',
'block' => 'sometimes|max:20',
'tahsil' => 'sometimes|max:20',
'village' => 'sometimes|max:20',
'maritalStatus' => 'required',
'spouseName' => 'sometimes|max:20',
'children' => 'sometimes|max:5|integer'
]);
$userInformationSave = new BauserInformation([
'userID' => \Auth::user()->id,
'fullname' => $request->get('fullname'),
'fatherName' => $request->get('fatherName'),
'Mothername' => $request->get('Mothername'),
'dobdate' => $request->get('dobdate'),
'dobmonth' => $request->get('dobmonth'),
'dobYear' => $request->get('dobYear'),
'caste' => $request->get('caste'),
'casteCertificateIs' => $request->get('casteCertificateIs'),
'emailAddress' => $request->get('emailAddress'),
'gender' => $request->get('gender'),
'handiCappedStatus' => $request->get('handiCappedStatus'),
'nationality' => $request->get('nationality'),
'state' => $request->get('state'),
'district' => $request->get('district'),
'block' => $request->get('block'),
'tahsil' => $request->get('tahsil'),
'village' => $request->get('village'),
'maritalStatus' => $request->get('maritalStatus'),
'spouseName' => $request->get('spouseName'),
'children' => $request->get('children')
]);
$userInformationSave->save();
return redirect()->route('home')->with('message', 'Your information is saved now');
}
The model is
class BauserInformation extends Model
{
protected $table = ['userFinalInformation'];
protected $fillable = ['userID', 'fullname', 'fatherName', 'Mothername', 'dobdate', 'dobmonth', 'dobYear', 'caste', 'casteCertificateIs', 'emailAddress', 'gender', 'handiCappedStatus', 'nationality', 'state', 'district', 'Block', 'tahsil', 'village', 'maritalStatus', 'spouseName', 'children'];
}
the error argument i am getting is
ErrorException (E_NOTICE)
Array to string conversion

You are complicating things.
On top of your controller put: use Illuminate\Support\Facades\Validator;.
Delete $userInformationSave.
Validate inputs:
$validator = Validator::make($request->all(), [
'fullname' => ['required', 'max:25'],
... every other input like I have done
]);
if ($validator->fails()) {
return redirect('/bla bla bla/create')->withErrors($validator);
}
And save the model:
BauserInformation::create($request->all());
EDIT #1
In you model, you should declare table and A_I like this:
protected $table = 'userFinalInformation';
protected $primaryKey = 'userID';
I think this will do the job.

Related

Laravel: Edit value only if it appears in the request?

in my app the user can update the info of stripe connected account, however I ONLY want to actullay update the value of the fields that appear in the request payload, I could do this with a simple if check but the way I update the stripe array method makes this issue more complicated .
Is there any syntax sugar or trick to make this easier.
How my update method looks;
public function editConnectedAccount(Request $request)
{
$account = Account::retrieve($request->connectedAccountId);
Account::update(
$request->connectedAccountId,
[
'type' => 'custom',
'country' => 'ES',
'email' => $request->userEmail,
'business_type' => 'individual',
'tos_acceptance' => [ 'date' => Carbon::now()->timestamp, 'ip' => '83.46.154.71' ],
'individual' =>
[
'dob' => [ 'day' => $request->userDOBday, 'month' => $request->userDOBmonth, 'year' => $request->userDOByear ],
'first_name' => $request->userName,
'email' => $request->userEmail,
'phone' => $request->userPhone,
'last_name' => $request->userSurname,
//'ssn_last_4' => 7871,
'address' => [ 'city' => $request->userBusinessCity, 'line1' => $request->userBusinessAddress, 'postal_code' => $request->userBusinessZipCode, 'state' => $request->userBusinessCity ]
],
'business_profile' =>
[
'mcc' => 5812, //got it
'description' => '',
//'url' => 'https://www.youtube.com/?hl=es&gl=ES', //got it
],
'capabilities' => [
'card_payments' => ['requested' => true],
'transfers' => ['requested' => true],
],
]
);
return response()->json([
'account' => $account,
], 200);
Consider using a Form Request where you preform validation. This will neaten up your controller for a start and also make validation (never trust user input!) reusable.
Assuming validation is successful, calling $request->validated() from inside your controller method will return only the fields present and validated. You can then use either fill($request->validated()) or update($request->validated()).

Laravel validation rules custom message with second level of array

Here my code :
$rules = [
'name' => 'required|string|max:255',
'price' => 'required|numeric|min:0',
'unit' => 'required|in:piece,kg,m',
'price_type' =>'required|string',
'service' => [
'string',
'required',
Rule::in($services_ids->all()),
],
'facility' => [
'string',
'required',
Rule::in($facilities_ids->all()),
],
'conciergeries' => [
'array',
'required',
Rule::in($conciergeries_ids->all()),
],
];
$custom_messages = [
'required' => 'Vous devez sélectionner un(e) :attribute.'
];
$validated = request()->validate($rules, $custom_messages);
The problem is that my custom_messages only works with 'name', 'price', 'unit', 'price_type' but not with 'service', 'facility' and 'conciergeries'.
Questions :
How to apply my custom messages with 'service', 'facility' and 'conciergeries' too ?
How to create a custom message for specifically one field ?
Thank's !
You just need to specify for which field you want to change the message
Try it like:-
$custom_messages = [
'service.required' => 'Your custom message for required service',
'service.string' => 'Your custom message of service should be string',];
And same process for facility and conciergeries.

Laravel Eloquent cannot insert to database

I'm making an app that runs like google form using Laravel 5.7. Here is the form table that i already made:
I made an eloquent model so that each Name in Personal details table has one record that contains all these table and insert filled table into database after click submit button. The problem is, it didn't successfully inserted into database. I don't know what's the problem, here are my codes:
PersonalDetails.php (eloquent model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class PersonalDetails extends Model
{
protected $table = 'personal_details';
protected $guarded = ['id'];
public function accomodation()
{
return $this->hasOne('App\Accomodation');
}
public function course()
{
return $this->hasOne('App\Course');
}
public function proposedStudy()
{
return $this->hasOne('App\ProposedStudy');
}
public function emergencyContact()
{
return $this->hasOne('App\EmergencyContact');
}
public function englishTestResult()
{
return $this->hasOne('App\EnglishTestResult');
}
public function homeInstitution()
{
return $this->hasOne('App\HomeInstitution');
}
public function insurance()
{
return $this->hasOne('App\Insurance');
}
}
FormController.php
public function submit(Request $request) {
$request->validate([
// Personal Details
'fullname' => 'required|string',
'nationality' => 'required|string',
'date_of_birth' => 'required|string',
'passport_number' => 'required|string',
'issuing_country' => 'required|string',
'date_of_issue' => 'required|string',
'date_of_expiry' => 'required|string',
'blood_type' => 'required|string',
'marital_status' => 'required|string',
'address' => 'required|string',
'city' => 'required|string',
'postal_code' => 'required|numeric',
'province' => 'required|string',
'country' => 'required|string',
'phone' => 'required|string',
'mobile' => 'required|string',
'email' => 'required|email',
'address2' => 'nullable|text',
'city2' => 'nullable|string',
'postal_code2' => 'nullable|numeric',
'province2' => 'nullable|string',
'country2' => 'nullable|string',
'phone2' => 'nullable|string',
'contact_name' => 'required|string',
// Home Institution
'name' => 'required|string',
'address' => 'required|string',
'phone' => 'required|string',
'email' => 'required|email',
'website' => 'required|string',
'faculty_dep' => 'required|string',
'start_year' => 'required|string',
'gpa' => 'required|string',
// Proposed Study
'semester' => 'required|in:Semester I (Aug-Jan),Semester II (Feb-Jun)',
'academic_year' => 'required|string',
'faculty' => 'required|string',
'department' => 'required|string',
'study_period' => 'required|string',
'start_date' => 'required|string',
'end_date' => 'required|string',
// Course
'course_title' => 'required|string',
'credit' => 'required|string',
// English Test Result
'test' => 'required|string',
'score' => 'required|numeric',
'test_center' => 'required|string',
'date_tested' => 'required|string',
// Insurance
'insurance_name' => 'required|string',
'validity' => 'required|string',
'cover' => 'required|string',
// Accomodation
'accomodation_help' => 'required|in:YES,NO',
'adress' => 'required|string',
'contact_person' => 'required|string',
// Contact of Emergency
'fullname' => 'required|string',
'relationship' => 'required|string',
'address' => 'required|string',
'phone' => 'required|string',
'mobile' => 'required|string',
'email' => 'required|email',
]);
PersonalDetails::create([
'fullname' => $request->input('name'),
'nationality' => $request->input('nationality'),
'date_of_birth' => $request->input('dob'),
'passport_number' => $request->input('passport'),
'issuing_country' => $request->input('is_country'),
'date_of_issue' => $request->input('doi'),
'date_of_expiry' => $request->input('doe'),
'blood_type' => $request->input('blood'),
'marital_status' => $request->input('maritial'),
'address' => $request->input('address'),
'city' => $request->input('city'),
'postal_code' => $request->input('postal'),
'province' => $request->input('state'),
'country' => $request->input('country'),
'phone' => $request->input('phone'),
'mobile' => $request->input('mobile'),
'email' => $request->input('email'),
'address2' => $request->input('address2'),
'city2' => $request->input('city2'),
'postal_code2' => $request->input('postal2'),
'province2' => $request->input('state2'),
'country2' => $request->input('country2'),
'phone2' => $request->input('phone2'),
'contact_name' => $request->input('contact_name'),
]);
HomeInstitution::create([
'name' => $request->input('institution'),
'address' => $request->input('i_address'),
'phone' => $request->input('i_phone'),
'email' => $request->input('i_email'),
'website' => $request->input('web'),
'faculty_dep' => $request->input('faculty_dept'),
'start_year' => $request->input('s_year'),
'gpa' => $request->input('gpa'),
]);
ProposedStudy::create([
'semester' => $request->input('duration'),
'academic_year' => $request->input('f_year') . '/' . $request->input('l_year'),
'faculty' => $request->input('faculty'),
'department' => $request->input('department'),
'study_period' => $request->input('spesific_period'),
'start_date' => $request->input('start_date'),
'end_date' => $request->input('end_date'),
]);
Course::create([
'course_title' => $request->input('course_1'),
'credit' => $request->input('credit_1'),
]);
EnglishTestResult::create([
'test' => $request->input('toefl'),
'score' => $request->input('score_toefl'),
'test_center' => $request->input('place_toefl'),
'date_tested' => $request->input('date_toefl'),
]);
Insurance::create([
'insurance_name' => $request->input('insurance'),
'validity' => $request->input('valid_date'),
'cover' => $request->input('cover'),
]);
Accomodation::create([
'accomodation_help' => $request->input('opt_acc'),
'adress' => $request->input('adress_acc'),
'contact_person' => $request->input('cp_acc'),
]);
EmergencyContact::create([
'fullname' => $request->input('emergency_name'),
'relationship' => $request->input('relationship'),
'address' => $request->input('address_emergency'),
'phone' => $request->input('emergency_phone'),
'mobile' => $request->input('emergency_mobile'),
'email' => $request->input('emergency_email'),
]);
// return back()-> with('success', 'Berhasil submit!');
}
Finally after all these struggles to figured out the problem, i just realized that i put wrong name in validation rules. The name on the left side of validation rules is different with name in html so i reformed the name in html and validation rules.
The big deal is i didn't put any validation error message after submit so that it won't inserted into database. After i put some error message, all of the field returned error that says "The :attribute is required". Simply because the name in validation is different with the html name :D
Thank you guys for helped me to figured out the problem, i worked it out :))
try with model path,if model folder is inside App then App\model;
eg:-
App\Insurance::create([
'insurance_name' => $request->input('insurance'),
'validity' => $request->input('valid_date'),
'cover' => $request->input('cover'),
]);
add $fillalbe in Model:
protected $fillable=['full_name','nationality','...']
you will need to specify fillalbe attribute on the model. read more at https://laravel.com/docs/5.7/eloquent#mass-assignment
Can you check your table migration or model relation, then revision your form controller.
I am create example from your code and successfull insert into database.
Personal Details Migration
Schema::create('personal_details', function (Blueprint $table) {
$table->increments('id');
$table->string('fullname')->nullable();
$table->string('nationality')->nullable();
$table->timestamps();
});
Home Institution Migration
Schema::create('home_institution', function (Blueprint $table) {
$table->integer('personal_details_id')->unsigned()->primary();
$table->string('name')->nullable();
$table->string('address')->nullable();
$table->timestamps();
#Foreign to Table Personal Details.
$table->foreign('personal_details_id')->references('id')->on('personal_details')->onUpdate('cascade')
->onDelete('cascade');
});
Personal Detail Model Relation
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PersonalDetails extends Model
{
protected $guarded = ['id'];
public function homeInstitution()
{
return $this->hasOne('App\HomeInstitution');
}
# Other your Relation
}
Form Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\PersonalDetails;
class FormController extends Controller
{
public function index()
{
return view('form.index');
}
public function submit(Request $request)
{
$request->validate([
// Personal Details
'fullname' => 'required|string',
'nationality' => 'required|string',
// Home Institution
'name' => 'required|string',
'address' => 'required|string',
]);
$pd = PersonalDetails::create(
['fullname' => $request->get('fullname'), 'nationality' => $request->get('nationality')]
);
# Insert into HomeInstitution => base on Model Relation from PersonalDetails
$pd->homeinstitution()->create(
['name' => $request->get('name'), 'address' => $request->get('address')]
);
# Insert into other youR relation
/*$pd->example()->create(
[]
);*/
return dd('Successfull Insert');
}
}
Maybe its can help you.

Laravel not storing phone number

I am working on a school project, and I have a registration form.
I am working in laravel 5 and am using the auth package of laravel.
I added my extra registration forms like this
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'lastName' => 'required|string|max:55|',
'streetAdress' => 'required|string|max:255|',
'houseNumber' => 'required|integer|min:1|',
'city' => 'required|string|max:255|',
'postal_code' => 'required|string|max:255|',
'user_phone_number' => 'required|numeric|min:10|',
'birth_day' => 'required|date|min:1|',
'user_parent_name' => 'required|string|max:255|',
'user_parent_email' => 'required|email|max:255|',
'user_parent_phone' => 'required|numeric|min:10|',
]);
}
That is my validator here is my create
protected function create(array $data)
{
$birthday = explode('-', $data['birth_day']);
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'lastName' => $data['lastName'],
'streetAdress' => $data['streetAdress'],
'houseNumber' => $data['houseNumber'],
'city' => $data['city'],
'user_phone_number' => $data['user_phone_number'],
'postal_code' => $data['postal_code'],
'birth_day_day' => $birthday[2],
'birth_day_month' => $birthday[1],
'birth_day_year' => $birthday[0],
'user_parent_name' => $data['user_parent_name'],
'user_parent_email' => $data['user_parent_email'],
'user_parent_phone' => $data['user_parent_phone'],
]);
}
Here is my html
<input id="user_phone_number" type="number" class="form-control" name="user_phone_number" value="{{ old('user_phone_number') }}" required>
In my database I have a column called user_phone_number. Everything else does store but the user_phone_number is still NULL
Thanks in advance
I was looking through my model and i found the problem. i didnt had the fillable option for user_phone_number,
protected $fillable = [
'name', 'email', 'password', 'lastName', 'streetAdress', 'houseNumber', 'city',
'postal_code', 'birth_day_year', 'user_phone_number', 'birth_day_month', 'birth_day_day', 'user_parent_name',
'user_parent_email', 'user_parent_phone',
];
Was missing user_phone_number
**if you are store phone no in database use this migration work for me
$table->bigInteger('phone');

laravel 5.2 set attribute name

How i set custom the attributte names in laravel 5.2 I already try this code, but doesn't work:
$attNames = array(
'code' => 'Número',
'contributor' => 'Nº Contribuinte',
'create_date' => 'Data criação',
'address' => 'Morada',
'zip_code' => 'Cod. Postal',
'city' => 'Localidade',
'email' => 'E-mail',
'phone_number' => 'Telefone',
'note' => 'Observações',
);
$validator = Validator::make($client, $this->rules,[],$attNames);
$validator->setAttributeNames($attNames);
if ($validator->fails()) {
// send back to the page with the input data and errors
$errors = $validator->messages();
return Redirect::to('/client/create')->withInput()->withErrors($errors);
}
You have passed wrong arguments to Validator::make.
You can pass only three arguments.
As per Documentation,
If needed, you may use custom error messages for validation instead of
the defaults. There are several ways to specify custom messages.
First, you may pass the custom messages as the third argument to the
Validator::make method.
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
I figure out.
controller:
use Validator;
(...)
$attName=array(
'code' => trans('validation.code'),
'contributor' => trans('validation.contributor'),
'create_date' => trans('validation.create_date'),
'address' => trans('validation.address'),
'zip_code' => trans('validation.zip_code'),
'city' => trans('validation.city'),
'email' => trans('validation.email'),
'phone_number' => trans('validation.phone_number'),
'note' => trans('validation.note'),
);
$validator = Validator::make($client, $this->rules, [], $attNames);
validation.php:
'attributes' => [
'code' => 'número',
'contributor' => 'nº contribuinte',
'create_date' => 'data criação',
'address' => 'morada',
'zip_code' => 'cod. postal',
'city' => 'localidade',
'email' => 'e-mail',
'phone_number' => 'telefone',
'note' => 'observações',
],

Categories