Inserting to multiple table with foreign key in Laravel Eloquent - php

These is my first time using the laravel framework and so far it is well structure than others i have used. But these have left me struck in an error i have been debugging a while.
I have a Post model that have sub model Post Images and Post Location. I am trying to insert data to the Post Images and then get the id of the save data into the base Model Post so i can make the relationship these are my code
Post Model
class Post extends Model {
protected $table = 'posts';
public $primaryKey = 'id';
public function user(){
return $this->belongsTo('App\User');
}
public function post_image(){
return $this->belongsTo('App\PostImage');
}
public function location(){
return $this->belongsTo('App\PostLocation');
}
}
Migrated From create post
public function up(){
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('user_id')->unsigned();
$table->integer('location_id')->unsigned();
$table->integer('post_image_id')->unsigned();
$table->timestamps();
});
Base model Relationship are
class PostImage extends Model{
protected $table = 'post_images';
public $primaryKey = 'id';
public function post(){
return $this->belongsTo('App\Post');
}
}
class PostLocation extends Model{
protected $table = 'location';
public $primaryKey = 'id';
public function post(){
return $this->belongsTo('App\Location');
}
}
In the Post Controller store method. I am saving the post image first and then try to reference the inserted table id as the foreign key and error occur after a while i try to different combination it doesnt work. The images are sucecfully save but the reference dosent work
Post controller store code
public function store(Request $request){
$this->validate($request, [
// Validation work here
]);
// Function to save images work perfectly and return the an array containg image
$images = $this->uploadAssetImages($request);
$post= new Post();
$image = new PostImage();
$image->image1 = $images[0];
$image->image2 = $images[1];
$image->image3 = $images[2];
$image->save();//$image->id()
//I have try these: $image_id = Response::json(array('success' => true, 'last_insert_id' => $image->id), 200);
$asset->description = $request->input('description');
$asset->user_id = auth()->user()->id;
$asset->post_image()->save($image);// After debuging error is found here
$asset->save();
Hope these can be resolve?

Related

Why is laravel push giving me a error 1364: Field 'question_entity_id' doesn't have a default value?

I'm very new to Laravel (this is my first time using it) and I'm trying to store some data that I made in a post request to my api. I keep on getting a General error: 1364 Field 'question_entity_id' doesn't have a default value.
I'm trying to use Laravel's push method to save the itemBank model and all it's relationships I define below but I get the error above. I've tried manually setting foreign_key relationships like `$itemBank->question_entity_id = $questionEntity->id' but this gives me the same error. I'm specifically trying to figure out why question_entity_id isn't getting filled (I know that the error could be resolved by making the field nullable or giving question_entity_id a default value).
Here are the relevant models:
class ItemBank extends Model
{
// table name
protected $table = "item_bank";
// do no use default timestamp fields
public $timestamps = false;
// item_bank relationships to other Models/tables
public function questionEntity() {
return $this->hasOne('App\QuestionEntity', 'id', 'question_entity_id');
}
public function optionEntity() {
return $this->hasMany('App\OptionEntity', 'item_id', 'id');
}
public function tagItemRel() {
return $this->hasOne('App\TagItemRel', 'item_id', 'id');
}
}
class QuestionEntity extends Model
{
// table name
protected $table = 'question_entity';
// disable default timestamps
public $timestamps = false;
public function itemBank() {
return $this->belongsTo('App\ItemBank', 'id', 'question_entity_id');
}
}
Here is the code where I'm trying to store my data:
public function store(Request $request)
{
$data = $request->all();
$itemBank = new ItemBank();
//save question body text
$questionEntity = new QuestionEntity();
$questionEntity->question = $data['questionBody'];
$itemBank->questionEntity()->save($questionEntity);
// save correct answer
$itemBank->correct_answers = $data['correctAnswer'];
//save question options
$choices = ['A', 'B', 'C', 'D'];
//$optionEntities = [];
foreach($choices as $choice) {
$optionEntity = new OptionEntity();
$optionEntity->choice = $data['choice' . $choice];
$optionEntity->choice_label = $choice;
$optionEntity->itemBank()->associate($itemBank);
}
//$itemBank->optionEntity()->saveMany($optionEntities);
//create new ItemTag Model
$itemTag = new ItemTag();
$itemTag->tag_name = $data['topic'];
//create new TagItemRel Model
$tagItemRel = new TagItemRel();
$tagItemRel->itemTag()->save($itemTag);
$tagItemRel->itemBank()->associate($itemBank);
$itemBank->push();
return $itemBank;
}
Here are the relevant migration files:
QuestionEntity:
Schema::create('question_entity', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('question', 500);
});
ItemBank:
Schema::create('item_bank', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('question_entity_id');
$table->string('correct_answers', 1);
$table->foreign('question_entity_id')->references('id')->on('question_entity');
});
Add question_entity_id in your ItemBank model, like this.
protected $fillable = [
'question_entity_id',
];
So your ItemBank model will look like this.
class ItemBank extends Model
{
// table name
protected $table = "item_bank";
protected $fillable = [
'question_entity_id','correct_answers'
];

Laravel 5.5: Getting id after insert

I have a model hotel.php to insert hotel data.insert data using create() but it dosen't return id, the returning collection hasn't id field!
Controller.php
/** "/user/2/create" */
public function store(User $user, HotelRequest $request)
{
$slug = (new hotel)->uniqueSlug( $request->name );
$request->merge([
'cat_id' => 1,
'slug' => $slug,
'created_by' => auth()->user()->id,
]);
$hotel = $user->hotels()->create( $request->all() );
dd($hotel);
................
hotel.php (model)
namespace App;
use Illuminate\Http\UploadedFile;
use Illuminate\Database\Eloquent\Model;
class hotel extends Model
{
protected $fillable = ['name', 'description','address','street','city','email',
'phone','web','cat_id','slug','created_by'];
protected $primaryKey = 'slug';
/**
unique slugs genarating
*/
protected $slug_guards = ['create','room'];
public $incrementing = false;
User.php (model)
public function hotels( )
{
return $this->hasmany('App\Hotel');
}
and the final result
It dosen't have id attribute. I need id to upload image!
NB: I changed that primarykey to default 'id' but no change in result.
Create_hotels... migration
public function up()
{
Schema::create('hotels', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->integer('created_by');
$table->integer('cat_id');
$table->string('name');
Your hotel model set the primary key as the slug :
protected $primaryKey = 'slug';
What i usually do, is for all my migrations, i set an autoincrements like following :
$table->increments('id');
this way laravel handles everything for you. Each create, update or whatever method handle the id of your items.
With this, you can then return the id of a stored data this way :
$id = create($data)->id;
where $data is your model with new datas. $id should now contain the id value of the newest stored model datas.
You have to change the Hotel model (or remove the whole line):
public $incrementing = true;
You are dumping the data you just inserted into the db which does not contain a id field.
create a show method in your Controller class as follows
public function show(User $user){
dd($user)
}
with a route as follows:
Route::get('user/{user}', 'Controller#show')
In hotel.php before the protected $fillable declaration try adding
protected $guarded = [
'id',
];
In your controllers store() method just after $slug = (new hotel)->uniqueSlug( $request->name );
try adding a $slug->save(); then returned slug should have an ID returned with it.
and/or possible the same similar strategy after line
$hotel = $user->hotels()->create( $request->all() );
by adding $hotel->save();
I changed the primarykey to default id and $incrementing = true; now its returning id of the created data. I changed whole methodes in Controller

Laravel 5.1 Delete relationships

My models relationship is oneToMany eg: PatientToSample
Patient_Model:
class Patient_Model extends Model implements Jsonable{
use SoftDeletes;
protected $table = 'patients';
public function samples(){
return $this->hasMany('App\Models\Sample_Model','code','patient_id');
}
}
Sample_Model :
class Sample_Model extends Model{
use SoftDeletes;
protected $table = 'samples';
public function patient(){
return $this->belongsTo('App\Models\Patient_Model','patient_id','code');
}
}
I think use the function delete Patient and Sample
public function delete(Request $request){
$patient = Patient_Model::withTrashed()
->where("id",$request->get("id"))
->delete();
return json_encode($patient);
}
But now only delete Patient....
This is one way to do it.
public function delete(Request $request){
$patient = Patient_Model::withTrashed()
->find($request->get("id"));
$patient->samples()->delete();
$patient->delete();
return json_encode($patient);
}
There is also a way to attach the relationship deletion to a delete event of the parent model, as discussed here.
Did you set constraints in migration?
Just write into Sample table migration row:
$table->foreign('patient_id')
->references('id')
->on('patients')
->onDelete('cascade');
For more info: Docs

How to store data using relation in laravel?

i have two table
posts
id|post_title|post_content
post_images
id|images|post_id
Controller
public function AddPost(Request $request)
{
Post::create($request->all());
// PostImage::create();
return Redirect::to('Post');
}
Also i have added Relation
class Post extends Model
{
protected $table = 'posts';
public function images()
{
return $this->hasMany('App\PostImage');
}
}
class PostImage extends Model
{
public function post()
{
return $this->belongsTo('App\Post');
}
}
I have one form where i adding post title ,post content and selecting multiple images. My question is how I can store post images along with post id in post_images table?
In you controller AddPost function try (using Form model binding)
$post = new Post($request->all());
PostImage::post()->images()->save($post);
Or you can also do like this I think
public function AddPost(Post $post, Request $request)
{
$input = Input::all();
$input['post_id'] = $post->id;
PostImage::create( $input );
return Redirect::to('Post');
}

How to insert data using relation?

I have two table
posts
id|post_title|post_content
post_images
id|images|post_id
Controller
public function AddPost(Request $request)
{
Post::create($request->all());
// PostImage::create();
return Redirect::to('Post');
}
Also i have added Relation
class Post extends Model
{
protected $table = 'posts';
public function images()
{
return $this->hasMany('App\PostImage');
}
}
class PostImage extends Model
{
public function post()
{
return $this->belongsTo('App\Post');
}
}
I have one form where i adding post title ,post content and selecting multiple images. My question is how I can store post images along with post id in post_images table?
Rewrite your code like this
class Post extends Model
{
protected $table = 'posts';
//add $fillable here
protected $fillable = ['post_title', 'post_content'];
public function images()
{
return $this->hasMany(App\PostImage::class);
}
}
class PostImage extends Model
{
protected $table = 'post_images';
//add $fillable here
protected $fillable = ['images', 'post_id'];
public function post()
{
return $this->belongsTo(App\Post::class);
}
}
Now in your controller
Post::create($request->all())->images()->create($request->all());
Here Post create saves your data to db also returns the object then
you accesses the relation images and saves data to images.
See here for more details One To Many

Categories