How to i insert foreign key to my database table - laravel

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: ''
})
}
},

Related

How to set multiple keys and relations for DataLoader with TypeORM?

OneToOne case
For one JoinColumn key in TypeORM, the #Extensions below can work with loader and loadkey.
But in this case, there are two JoinColumn keys: postId and version. How to set them into #Extensions?
#OneToOne(() => PostVersion, {
lazy: true,
cascade: true,
createForeignKeyConstraints: false,
})
#JoinColumn([
{ name: 'id', referencedColumnName: 'postId' },
{ name: 'version', referencedColumnName: 'version' },
])
#Field(() => PostVersion, {
middleware: [dataloaderFieldMiddleware],
})
// How to set both postId and version keys below?
#Extensions({
loader: (dataloaders: IDataloaders) => dataloaders.currentPostVersion,
loadKey: (post: Post) => post.id,
})
current: Promise<PostVersion>;
ManyToMany case
For many to many relation, one side can set #Extensions with one key. Is it right to set the other relation key on the other side in #Extensions?
#ManyToMany(() => Type)
#JoinTable({
name: 'types_posts',
joinColumn: {
name: 'post_id',
referencedColumnName: 'id',
},
inverseJoinColumn: {
name: 'type_id',
referencedColumnName: 'id',
},
})
#Field(() => [Type], {
middleware: [dataloaderFieldMiddleware],
})
// How to set many to many relations keys with dataloader here?
#Extensions({
loader: (dataloaders: IDataloaders) => dataloaders.typeByPostId,
loadKey: (post: Post) => post.id,
})
postboards: Promise<Type[]>;

How to create endpoint to post data and the response is nested array in Laravel 8

I'm a beginner in Laravel and I would like to make API with the response like this
elements: [
{
title:
"Please indicate if you agree or disagree with the following statements",
question: [
{
value: "affordable",
text: "Product is affordable",
},
{
value: "does what it claims",
text: "Product does what it claims",
},
{
value: "better then others",
text: "Product is better than other products on the market",
},
{
value: "easy to use",
text: "Product is easy to use",
},
],
},
],
here's code in my migration database :
Schema::create('question_surveys', function (Blueprint $table) {
$table->id('question_survey_id');
$table->string('title');
$table->json('question');
$table->timestamps();
});
and in my controller, for store the data that I have created, I tried this
$validation = $request->validation([
'title' => 'required|string',
'question' => 'required|json',
]);
try {
$response = QuestionSurvey::create($validation);
return response()->json([
'success' => true,
'message' => 'Survey Question Successfully Created',
'data' => $response,
'code' => 200
], 200);
} catch (\Exception $e) {
return response()->json([
'message' => 'Something wrong, content was not created successfully',
'errors' => $e->getMessage()
]);
}
I tried to post data in postman, the code return 200 but not successfully created. I'm confused what should I do and what the exactly keyword I should search on google to solve this problem. I'm very thankful if you can help me to solve this problem..
instead of these code you can create a table questions and relate it with question_surveys, One To Many Relationships, like:
first create table questions and set value and text as columns, then just add a foreign key to question_surveys tabel like: $table->foreignId('question_survey_id'); in the migration.
now you have to ways. 1- create spread CRUD for questions or in store question_surveys send all questions in an array, after store question_surveys store questions with foreign key, question_survey_id.
in the question_surveys model write:
public function question()
{
return $this->hasMany(Question::class);
}
and in Question model write:
public function question_surveys()
{
return $this->belongsTo(QuestionSurvey::class);
}
now when you find QuestionSurvey:
$question_survey = QuestionSurvey:://your query;
$question_survey->question; // get all questions related to this `question_surveys`
not: if $question_survey is array, put $question_survey->question in resource.

Laravel Backpack store image

I'm trying to store an image using Backpack's CRUD.
The Model's name is ProductModel, and in the SetupCreateOperation, I have:
CRUD::addField([
'name' => 'photo',
'label' => 'Foto',
'type' => 'image'
]);
When I try to upload an image, I get an error saying the following.
String data, right truncated: 1406 Data too long for column 'photo.'
Indeed the string being passed is almost 7000 characters long.
Model
class ProductModel extends Model
{
use \Backpack\CRUD\app\Models\Traits\CrudTrait;
use HasFactory;
protected $guarded = [];
public function products()
{
return $this->hasMany('App\Models\SoldProduct',
'product_model_id', 'id');
}
}
Migration
Schema::create('product_models', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('photo'); //path
$table->integer('stock');
$table->integer('limited_edition_pieces');
$table->decimal('price', 8, 2);
$table->string('note')->nullable();
$table->timestamps();
});
What should I do?
In order to set Image you need to add Field like this
$this->crud->addField([
'name' => 'image',
'label' => 'Image',
'type' => 'upload',
'upload' => true
]);
use 'disk' => 'uploads' if you want to upload to s3(amazon), otherwise don't add it if you want to keep images in public folder.
Also keep in mind that your image attribute needs to be set in your model.
Like this,
public function setImageAttribute($value)
{
$attribute_name = "image";
// you can check here if file is recieved or not using hasFile()
$disk = "public";
$destination_path = "/uploads";
$this->uploadFileToDisk($value, $attribute_name, $disk, $destination_path);
}
The uploadFileToDisk() lies in your Backpack\CRUD\app\Models\Traits\CrudTrait which you have already added

Laravel updating relational table not working

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

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