Laravel updating relational table not working - laravel

Question 1: Unable to update the record for relational table profiles. End up with the following error.
Error
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'field list' (SQL: update users set user_id = 132, users.updated_at = 2020-03-30 08:48:51 where id = 132)
I have two tables users and profiles with below schema
User Schema
Schema::create(
'users',
function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->enum('role', ['super', 'admin', 'manager', 'subscriber', 'user'])->default('user');
$table->boolean('is_root')->default(FALSE);
$table->rememberToken();
$table->timestamps();
$table->unique(['username', 'email'], 'users_unique_credentials');
}
);
Profile Schema
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->string('key', 191);
$table->longText('value')->nullable();
$table->foreign('user_id', 'profile_uid_fk')
->references('id')
->on('users')
->onDelete('cascade');
$table->unique(['user_id', 'key'], 'profile_unique_key');
});
User Modal - Relation
public function profiles()
{
return $this->hasMany(Profile::class)->orderBy('id');
}
Profile Modal - Relation
public function user()
{
return $this->belongsTo(User::class);
}
User Controller - Update
public function update(UserRequest $request, User $user)
{
$user->email = $request->email;
$user->role = $request->role;
if ($request->has('password')) {
$user->password = Hash::make($request->password);
}
$user->save();
$user->profile()->save($user);
}
dd - $request->all()
Question 2: the user_id is a hidden field in the form. However, I would prefer to pass it from the controller instead. Is there any
way to do it?
array:15 [▼
"_token" => "O3Ardvzz7QvAsYa7aUWn4dbJx1qpCsScykD1fh1S"
"_method" => "PUT"
"email" => "newage#test.com"
"password" => null
"password_confirmation" => null
"role" => "subscriber"
"first_name" => "John"
"last_name" => "doe"
"city" => "Ahmedabad"
"mobile" => "545466555"
"facebook" => "https://facebook.com/profile/pp"
"twitter" => "https://twitter.com"
"youtube" => null
"instagram" => null
"user_id" => "132"
]

you need to change query in user controller to :
$user->profile()->create($user->toArray())->save();
you can also see this Example

You can use the associate method.
$user->profile()->associate($user);
For more info: Docs

Related

Save multiple data in database column from select multiple

I want to save more than one university under one student. For html select I used
<select class="selectpicker" multiple data-live-search="true" name="university">
#foreach($districts as $row)
<option value= {{$row->name}} > {{$row->name}} </option>
#endforeach
</select>
This taking previously saved university. I am using district as university.
Controller->
public function store(Request $request)
{
Seller_info::create([
'name' => $request['name'],
'email' => $request['email'],
'passport' => $request['passport'],
'phone_number' => $request['phone_number'],
'address' => $request['address'],
'dateofbirth' => $request['dateofbirth'],
'ielts' => $request['ielts'],
'openingcharge' => $request['openingcharge'],
'serviceCharge' => $request['serviceCharge'],
'applydate' => $request['applydate'],
'visaStatus'=> $request['visaStatus'],
'country' => $request['country'],
'university'=> $request['university'],
]);
return back();
}
This is saving the students. This is a mishmash code I am sorry about that. I am working on a different for fast learning. Here I am using seller_info as student.
The data is is saving university but only one university in the database. I tried to use for loop in case of storing. But could not able to implement it properly.
My table file->
Schema::create('seller_infos', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('email')->unique();
$table->string('passport')->nullable();
$table->string('phone_number')->unique();
$table->string('address')->nullable();
$table->string('dateofbirth')->nullable();
$table->string('ielts')->nullable();
$table->string('openingcharge')->nullable();
$table->string('serviceCharge')->nullable();
$table->string('applydate')->nullable();
$table->string('visaStatus')->nullable();
$table->string('country')->nullable();
$table->string('university')->nullable();
$table->timestamps();
});
And model
protected $fillable = [
'name', 'email', 'passport', 'phone_number','address','dateofbirth','ielts', 'openingcharge','serviceCharge','applydate',
'visaStatus','country','university'
];
If you want to store multiple university data for one student first of all you need 3 table, students(so your Seller Info), universities and seller_info_university(will be pivot table),
seller_info_university Migration must be like;
Schema::create('seller_info_university', function (Blueprint $table) {
$table->bigInteger('seller_info_id')->unsigned();
$table->bigInteger('university_id')->unsigned();
});
Add this code your SellerInfo Model;
public function universities()
{
return $this->belongsToMany(University::class); // Your University model
}
Add this code your University Model;
public function students()
{
return $this->belongsToMany(SellerInfo::class); // Your Student(SellerInfo) model
}
In your Controller try this
$student = Seller_info::create([
'name' => $request['name'],
'email' => $request['email'],
'passport' => $request['passport'],
'phone_number' => $request['phone_number'],
'address' => $request['address'],
'dateofbirth' => $request['dateofbirth'],
'ielts' => $request['ielts'],
'openingcharge' => $request['openingcharge'],
'serviceCharge' => $request['serviceCharge'],
'applydate' => $request['applydate'],
'visaStatus'=> $request['visaStatus'],
'country' => $request['country'],
// 'university'=> $request['university'], you dont need there anymore
]);
$student->universities()->attach($request['universities']); // You can use attach(), detach() or sync() functions, you can search in Laravel Documentation
return back();
And View;
<select class="selectpicker" multiple data-live-search="true" name="universities[]">
#foreach($districts as $row)
<option value= {{$row->name}} > {{$row->name}} </option>
#endforeach
</select>

How to i insert foreign key to my database table

I have two table having relationship but when I do send data into database I got NULL, I am using Vuejs with Laravel normally in laravel I may use foreach loop to do so but I am a beginner with laravel & Vuejs
My two tables are students and parent, I have a foreign key at student table that references parent id
Anyone one who can help me how go through this
My problem is when i send data the foreign key at student table is inserted as NULL
This is my student model:
protected $fillable = [
'pregistration_id',
'admission_no',
'fname',
'mname',
'lname',
'dob',
'gender',
'primary_school',
'form_enrolled',
'transfered_from',
'transfered_to',
];
This is my parent model:
protected $fillable = [
'fname',
'mname',
'lname',
'residence',
'phone',
'occupation',
];
This is my student controller:
return Student::create([
'pregistration_id'=>$request['pregistration_id'],
'admission_no'=>$request['admission_no'],
'fname'=>$request['fname'],
'mname'=>$request['mname'],
'lname'=>$request['lname'],
'dob'=>$request['dob'],
'gender'=>$request['gender'],
'primary_school'=>$request['primary_school'],
'form_enrolled'=>$request['form_enrolled'],
'transfered_from'=>$request['transfered_from'],
'transfered_to'=>$request['transfered_to'],
// dd($request->all())
]);
This is my students table:
Schema::create('students', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('pregistration_id')->unsigned()->nullable();
$table->integer('admission_no')->unique();
$table->string('fname');
$table->string('mname');
$table->string('lname');
$table->date('dob');
$table->string('gender');
$table->string('primary_school');
$table->string('form_enrolled');
$table->string('transfered_from');
$table->string('transfered_to');
$table->foreign('pregistration_id')->references('id')->on('pregistrations');
$table->timestamps();
});
This is a part of student component in Vue:
data() {
return {
editmode: false,
students: {},
form: new Form({
id: '',
admission_no: '',
fname: '',
mname: '',
lname: '',
dob: '',
gender: '',
primary_school: '',
form_enrolled: '',
trasfered_from:'',
trasfered_to: ''
})
}
},

Laravel updateOrCreate with composite key

I have a table that's defined thus:
Schema::create('tableA', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('label_id')->unsigned();
$table->date('date');
$table->integer('value');
$table->unique(['user_id','label_id','date']);
$table->timestamps();
});
The table uses a composite key of user_id, label_id and date.
I would like to update the table using the Model::updateOrCreate method thus:
Model::updateOrCreate(
[
'user_id' => $user_id,
'label_id' => $label_id,
'date' => $date,
'value' => $value,
]);
But I get an error if I run the method when a row with the composite key already exists because it seems Laravel doesn't work with composite keys.
For example row
[
user_id:2,
label_id:3,
date:'2019-04-04',
value: 44
]
cannot be updated using
Model::updateOrCreate([
user_id:2,
label_id:3,
date:'2019-04-04',
value: 100
]);
Does this mean there's no way to use updateOrCreate and I need to check each row if it exists before I attempt to add it ?
If you want to update a row based on a user_id the first parameter of the updateOrCreate is an array of fields you are looking to match, and the second contains fields that should update. So from what you are saying I believe you should use this:
Model::updateOrCreate([
user_id => 2,
label_id => 3,
date => new Carbon('2019-04-04')
],
[
value => 100
]);

Insert null in date field in postgresql using collection

I am trying to insert an array with date field - end_date in postgresql with Laravel 5.7. But this gives an error -
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column \"end_date\" violates not-null constraint
I am using Laravel 5.7, Postgresql 9.3
$array = [
"amazon_store_id" => 4
"advertising_profile_id" => 1
"campaign_id" => 123
"name" => "6 shelf 2"
"campaign_type" => "sponsoredProducts"
"targeting_type" => "manual"
"premium_bid_adjustment" => true
"daily_budget" => 15.0
"start_date" => "2014-11-25 09:32:18"
"end_date" => null
"state" => "paused"
"serving_status" => "CAMPAIGN_PAUSED"
"creation_date" => "2014-11-07 10:17:03"
"last_updated_date" => "2018-10-24 12:49:54"
"created_at" => "2018-12-24 09:32:18"
"updated_at" => "2018-12-24 09:32:18"
];
DB::table($table_name)->insert($array->toArray());
Ideally it shall insert the null in the database.
In your migration you can do this to make the column nullable:
public function up()
{
Schema::create('tablename', function (Blueprint $table) {
$table->dateTime('end_date')->nullable();
});
}
->nullable() Designate that the column allows NULL values
In your migration file you have to define the date field as nullable.
Schema::table($table_name, function (Blueprint $table) {
$table->dateTime('end_date')->nullable();
});

Storing data to multiple tables from single form in laravel

My schemas are:
Schema::create('persons', function (Blueprint $table) {
$table->bigInteger('university_id')->unique()->unsigned();
$table->string('category');
$table->string('name');
$table->timestamps();
});
Schema::create('teachers', function (Blueprint $table) {
$table->increments('teacher_id');
$table->bigInteger('university_id')->unsigned();
$table->string('position');
$table->string('courses');
$table->integer('salary');
$table->timestamps();
});
Schema::create('students', function (Blueprint $table) {
$table->increments('student_id');
$table->bigInteger('university_id')->unsigned();
$table->string('year');
$table->string('semester');
$table->string('programme');
$table->integer('rollNum');
$table->timestamps();
});
I have a two forms with fields:
For Teachers:University ID, Name, Category, Position, Courses, Salary
For Students:University ID, Name, Category, Year, Semester, Programme, Roll Number
I tried to store data in the database through my controller in single method as follows:
After requesting all data into variables from form, I tried to store data in the following way.
University::create([
'university_id' =>$universityID,
'category' => $category,
'name' => $name
]);
//I passed values of category as Teacher when submitting from teacher form
//and Student while submitting student form.
if($category == 'Teacher'){
Teacher::create([
'university_id' => $universityID,
'position' => $position,
'courses' => $course,
'salary' => $salary
]);
}
if($category == 'Student'){
Student::create([
'university_id' => $universityID,
'year' => $year,
'semester' => $semester,
'programme' => $programme,
'rollNum' => $roll
]);
}
When i submitted Teacher's form, I was expecting that data will be stored in University and Teachers table only and it did. But there was an unexpected problem occurred. The Student table was filled with Null values. I was expecting if condition will prevent running Student::create([])
So how can I store values only in University and Teachers table when submitting from teachers form and University and Students table only when submitting from students form without having null values in either of them.
Instead of using like this, simple would be use if and else statements and that would do the job.
Example:
$university = University::create([
'university_id' =>$universityID,
'category' => $category,
'name' => $name
]);
if($category == 'Teacher') {
Teacher::create([
'university_id' => $university->id,
'position' => $position,
'courses' => $course,
'salary' => $salary
]);
else if($category == 'Student') {
Student::create([
'university_id' => $university->id,
'year' => $year,
'semester' => $semester,
'programme' => $programme,
'rollNum' => $roll
]);
}else{
//Unknown Category name
}
Let me know if that works for you. The way I see it's very simple and straight forward.

Resources