2
votes

I'm using Laravel and I'm trying to create a related record from an array using the method HasOne::create. It inserts the related record, but does not add a new id to main model's foreign field. What am I doing wrong?

Thx

    $contact = new Contact();

    $contact->company = $data['company'] ?? '';
    $contact->comment = $data['comment'] ?? '';

    $contact->save();

    $contact->address()->create($data['address']);

    ...

    var_dump($contact->address_id); exit();

The relations work fine, all fields specified. By ->get() methods they're returning correct models

var_dump result - null

Also, the $data['address'] contains valid data, specified as fillable at Address model and address_id is fillable for Contact model

UPD:

Contact class:

public function address()
{
    return $this->hasOne(Address::class, 'id', 'address_id');
}

Address class:

    public function contact()
{
    return $this->belongsTo(Contact::class, 'id', 'address_id');
}

$data['address'] contains an array with ['raw' => 'someaddress'], raw field is in $fillable

1
Please, post how you defined the relationships in the models. Also an example of how it is formed $data['address'].porloscerros Ψ
@porloscerrosΨ AddedHungryCat
I think for that to work, you should have a 'contact_id' field in your 'addresses' table, and not an 'address_id' field in the 'contacts' table. Because the relationship is "One Contact has One Address" and "One Address belongs to One Contact".porloscerros Ψ

1 Answers

1
votes

There's a nice guide on Eloquent Relationships here.

Based on that I just tested the code below and it works fine (using Laravel 5.8)

Migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class Cars extends Migration
{

    public function up()
    {
        Schema::create('owners', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

        Schema::create('cars', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();

            $table->integer('owner_id')->unsigned()->index()->nullable();
            $table->foreign('owner_id')->references('id')->on('owners');
        });
    }

    public function down()
    {
        Schema::drop('cars');
        Schema::drop('owners');
    }
}

Models

//App/Owner.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Owner extends Model
{
    protected $fillable = ['name'];

    public function car()
    {
        return $this->hasOne(Car::class);
    }

}

//App/Car.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    protected $fillable = ['name'];

    public function owner()
    {
        return $this->belongsTo(Owner::class);
    }
}

Test

<?php

namespace Tests\Feature;

use App\Owner;
use Tests\TestCase;

class TestCars extends TestCase
{
    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function testExample()
    {
        $owner = new Owner(['name' => 'Jack']);
        $owner->save();

        $owner->car()->create(['name' => 'Nice Car']);
    }
}

SQL

select * from cars;
------------
# id, name, created_at, updated_at, owner_id
'1', 'Nice Car', '2019-06-21 13:08:58', '2019-06-21 13:08:58', '1'

select * from owners
-------------
# id, name, created_at, updated_at
'1', 'Jack', '2019-06-21 13:08:58', '2019-06-21 13:08:58'