Laravel Eloquent cannot insert to database - php

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.

Related

Get API errors from Laravel into Flutter

I'm using this code for User Sign Up in Laravel:
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'phone' => $validatedData['phone'],
'type' => $validatedData['type'],
'verified' => $validatedData['verified'],
'password' => Hash::make($validatedData['password']),
]);
$token = $user->createToken('auth_token')->accessToken;
return response()->json([
'user' => $user,
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
As you can see , some of my field are unique , so I want to display a message in my front side that displays the error from the back side.
Exemple : When a user enters a used phone number , I want to return an error saying : this phone number has been used .
How can I achieve this ? Thank you.
You can get a User record from the database by phone. If the record exists, then do your logic
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
// get a user record by phone
$record = User::where('phone', $validatedData['phone'])->find();
if (!empty($record)) {
return response()->json([
'error' => 'this phone number has been used'
])
}
//.....
}

Laravel crud, update error (Call to a member function update() on null)

So, I'm trying to make update function, using this
public function editProfile(Request $request, $id)
{
// Validating
$request->validate([
// 'username' => 'nullable|unique:users|min:4',
// 'email' => 'nullable|unique:users|email:rfc,dns',
'contact_phone' => 'nullable|digits_between:9,12',
'bio_en' => 'nullable',
'bio_ar' => 'nullable',
'icon' => 'nullable',
'logo' => 'nullable',
'plan_id' => 'required',
'category_id' => 'required',
'is_local' => 'required',
]);
$user = User::find($id);
$user->update([
'username' => $request->username,
'email' => $request->email,
'contact_phone' => $request->contact_phone,
'bio_en' => $request->bio_en,
'bio_ar' => $request->bio_ar,
'logo' => $request->logo,
'icon' => $request->icon,
'plan_id' => $request->plan_id,
'category_id' => $request->category_id,
'referred_by_id' => Auth::user()->id,
]);
if ($user) {
return back()->with("success", __("editedSuccessfully"));
} else {
return back()->with('error', __("somethingWentWrongTryAgainLater"));
}
}
but I get the error
Call to a member function update() on null
shows on line $user->update
hope anyone can help me
It returns null because it cannot find the user with User::find($id). Check that you have a user by $id

Per row validation while importing CSV file

I'm Importing a CSV file to a livewire component and trying to run some validation for each row of the file but I'm having problems doing this. It seems that my validation is doing nothing.
Here is how my Livewire component looks like:
namespace App\Http\Livewire\Modals;
use Validator;
use Livewire\Component;
use App\Http\Traits\Csv;
use App\Models\AccountUser;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
class ImportExtensions extends Component
{
use WithFileUploads;
public $clientID;
public $showModal = false;
public $upload;
public $columns;
public $fieldColumnMap = [
'first_name' => '',
'last_name' => '',
'email' => '',
'password' => '',
'extension' => '',
'user_type' => '',
];
protected $rules = [
'fieldColumnMap.first_name' => 'required|max:255',
'fieldColumnMap.last_name' => 'required|max:255',
'fieldColumnMap.email' => 'required|max:255',
'fieldColumnMap.password' => 'required|max:255',
'fieldColumnMap.extension' => 'required|max:255',
'fieldColumnMap.user_type' => 'required|max:255',
];
protected $validationAttributes = [
'fieldColumnMap.first_name' => 'First Name',
'fieldColumnMap.last_name' => 'Last Name',
'fieldColumnMap.email' => 'Email',
'fieldColumnMap.password' => 'Password',
'fieldColumnMap.extension' => 'Extension',
'fieldColumnMap.user_type' => 'User Type',
];
public function updatingUpload($value)
{
Validator::make(
['upload' => $value],
['upload' => 'required|mimes:txt,csv'],
)->validate();
}
public function updatedUpload()
{
$this->columns = Csv::from($this->upload)->columns();
$this->guessWhichColumnsMapToWhichFields();
}
public function import()
{
// Validate that you are importing any data
$this->validate();
$importCount = 0;
Csv::from($this->upload)
->eachRow( function ($row) use (&$importCount){
$eachRow = $this->extractFieldsFromRow($row);
//Validate the data of each Row to make to make sure you don't import duplicate records
$this->validateOnly(collect($eachRow), [
'fieldColumnMap.first_name' => 'required|max:255',
'fieldColumnMap.last_name' => 'required|max:255',
'fieldColumnMap.email' => 'required|max:255|email|unique:account_users, email',
'fieldColumnMap.extension' => 'required|numeric|unique:account_users, extension',
'fieldColumnMap.password' => 'required|max:255',
'fieldColumnMap.user_type' => 'required|in:user,admin',
]);
//If validation fails, it should skip the create extension part and run the next row
//If validation pass, then create the Extension
AccountUser::create([
'user_id' => Auth::user()->id,
'account_id' => $this->clientID,
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
]);
$importCount++;
});
$this->reset();
$this->emit('refreshExtensions');
$this->notify('Successfully Imported '.$importCount.' Extensions');
}
Also, how can I make so that if the validation fails it goes to the next row instead of trying to create the extension.
Thanks.
I was able to create custom rules for just this. if one row fails validation, I just throw an error. So, basically either all rows pass or all fails.
Here is how it looks like now:
public function import()
{
// Validate that you are importing any data
$this->validate();
$importCount = 0;
Csv::from($this->upload)
->eachRow( function ($row) use (&$importCount){
$eachRow = $this->extractFieldsFromRow($row);
$validatedData = Validator::make([
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
],[
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:account_users',
'extension' => 'required|numeric|unique:account_users',
'password' => 'required|max:255',
'user_type' => 'required|in:user,admin',
],);
if($validatedData->fails()){
$this->notify(['error','Oops something went wrong!']);
}else{
AccountUser::create([
'user_id' => Auth::user()->id,
'account_id' => $this->clientID,
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
]);
$importCount++;
}
});
$this->reset();
$this->emit('refreshExtensions');
if($importCount!=0) $this->notify(['success','Successfully Imported '.$importCount.' Extensions']);
}

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 - Call to a member function create() on null

I am trying to save form details into my database, through a controller. When I click submit, I am shown this error:
in ClinicController.php line 58 at
ClinicController->store(object(Request))
Line 58 (See below for the entire function) is:
$request->user()->create([
Controller:
public function store(Request $request)
{
$request->user()->create([
'name' => $request->name,
'email' => $request->email,
'password' => $request->password
]);
$request->user()->clinic()->create([
'clinic_name' => $request->clinic_name,
'telephone' => $request->telephone,
'address_1' => $request->address_1,
'address_2' => $request->address_2,
'city' => $request->city,
'postcode' => $request->postcode
]);
return redirect('/home');
}
User Model:
public function clinic() {
return $this->belongsTo(Clinic::class);
}
Clinic Model:
public function user() {
return $this->belongsTo(User::class);
}
Routes.php:
Route::post('/clinic', 'ClinicController#store');
Any help would be hugely appreciated. Many thanks.
public function store(Request $request)
{
$user = App\User::create([
'name' => $request->name,
'email' => $request->email,
'password' => $request->password
]);
$clinic = App\Clinic::create([
'clinic_name' => $request->clinic_name,
'telephone' => $request->telephone,
'address_1' => $request->address_1,
'address_2' => $request->address_2,
'city' => $request->city,
'postcode' => $request->postcode
])
$user->clinics()->attach($clinic->id);
return redirect('/home');
}
If you want the currently authorized user, just use app()->user(). Also, you can simplify a lot of your logic and make it much easier to read.
auth()
->user()
->create($request->only([
'name',
'email',
'password'
]))
->clinic()
->create($request->only([
'clinic_name',
'telephone',
'address_1',
'address_2',
'city',
'postcode'
]));
return redirect('/home');
Change your controller to this:
public function store(Request $request)
{
App\User::create([
'name' => $request->name,
'email' => $request->email,
'password' => $request->password
]);
App\Clinic::create([
'clinic_name' => $request->clinic_name,
'telephone' => $request->telephone,
'address_1' => $request->address_1,
'address_2' => $request->address_2,
'city' => $request->city,
'postcode' => $request->postcode
]);
return redirect('/home');
}
I think problems with $fillable property, make sure to check it.
$user = App\User::create([
'name' => $request->name,
'email' => $request->email,
'password' => $request->password
]);
$user->clinic()->create([
'clinic_name' => $request->clinic_name,
'telephone' => $request->telephone,
'address_1' => $request->address_1,
'address_2' => $request->address_2,
'city' => $request->city,
'postcode' => $request->postcode
]);
return redirect('/home');

Categories