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();
});
}
from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel5-5-insert-the-id-of-the-created-model-to-create-a-record-in-another-table/
via Lzo Media
No comments:
Post a Comment