K
K
kupurim2018-11-27 15:20:49
Laravel
kupurim, 2018-11-27 15:20:49

How to implement normal insert into a table with relationships in laravel?

Hello.
There is a table with records (post) the post_support table is associated with it for relation to the support table.
I asked for the implementation idea here .

Links picture
5bf3ff8f2e108497548276.png

Made a migration for post_support:
Migration code
Schema::create('post_support', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id')->unsigned();
            $table->integer('support_id');

            $table->foreign('post_id')->references('id')->on('post');
 });


Further, in the Post model, I registered the connection.
The code
public function supports() {
        return $this->hasMany('App\PostSupport');
}


Everything seems to be fine so far, the data output is happening as it should, but when saving, it gives the error
"MassAssignmentException in Model.php line 444: support_id"
Save code
$post = App\Post::find($page_id);
foreach ($request->input('support_id') as $id) {
    $post->supports()->save(
        new App\PostSupport(['support_id' => $id])
    ); 
}


Of course, you can insert directly through DB::table('post_support')->insert([]) but I wonder what the problem is.
Question 2.
When updating a record, I can only change the fields with supports and when I save, an error is displayed that the record has not been updated. The code:
if( DB::table('post')->where('id', '=', $page_id)->update($data) ) {
    echo "ok";
}

Here it’s clear why the message is not displayed, I insert records in post_support above, but first delete everything - DB::table('post_support')->where('post_id', '=', $page_id)->delete() ;
How can you do it right?
Thanks for the help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mokhirjon Naimov, 2018-11-27
@zvermafia

  • Mass Assignments
  • many to many
  • Many To Many Relationships

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question