Alladin
Alladin

Reputation: 1072

Laravel5.5: Insert the ID of the created model to create a record in another table

I have been trying to create a record of a table B using the id of a created record in table A. But for some reason, the field is always null even though i have dumped the value of the model id and it's correct. but when i assign it to a field in table B it doesn't insert it. I don't get any errors, and both records are created(in Table A and B) but the value of the field that is supposed to have the ID of model A is NULL.

I have added the field to the $fillable array in the model class:

protected $fillable = [
        'name', 'email', 'password', 'phone', 'role', 'A_id', 
    ];

Here is the code I tried. Please help me solve this issue.

if($data['role'] == 'admin'){

            $tableA = TableA::create([
                'name' => $data['name'],
                'phone' =>$data['phone']
            ]);
            return TableB::create([
                'A_id' => $tableA->id,
                'name' => $data['nameB'],
                'email' => $data['email'],
                'role' => $data['role'],
                'phone' => $data['phoneB'],
                'password' => bcrypt($data['password']),
            ]);
        }

Here is the migration file for TableB

public function up()
    {
        Schema::create('tableB', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('A_id')->unsigned()->nullable();
            $table->string('phone', 10)->unique();
            $table->string('name');
            $table->string('role');
            $table->integer('address_id')->nullable();
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });
    }

Upvotes: 1

Views: 33

Answers (2)

Alladin
Alladin

Reputation: 1072

After Being confused for quite some time. I have tried a different way to create the model and for some reason, it's just working fine.

if($data['role'] == 'admin'){

    $tableA = TableA::create([
        'name' => $data['name'],
        'phone' =>$data['phone']
    ]);

    $tableB = new TableB();
    $tableB->A_id = $tableA->id;
    $tableB->name = $data['nameB'];
    $tableB->email = $data['email'];
    $tableB->role = $data['role'];
    $tableB->phone = $data['phoneB'];
    $tableB->password = bcrypt($data['password']);
    $tableB->save();
    return $tableB;
}

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

Add A_id to the $fillable array in the TableB model:

protected $fillable = ['A_id', ......];

Upvotes: 2

Related Questions