ChrisF79
1 month ago

How to save to a database with multiple tables?

Posted 1 month ago by ChrisF79

I have a Users table and an Address (mailing address) table and I have the relationships set up as such:

User Model

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];


    public function address()
    {
        return $this->hasMany('App\Address', 'user_id');
    }
}

User Migration

        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('first_name');
            $table->string('last_name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

Address Model

class Address extends Model
{
    public function address_type()
    {
        return $this->hasOne('App\AddressType');
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Address Migration

        Schema::create('addresses', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('address_type');
            $table->unsignedBigInteger('user_id');
            $table->string('address_1');
            $table->string('address_2')->nullable();
            $table->string('address_3')->nullable();
            $table->string('city');
            $table->string('state_or_province');
            $table->string('postal_code');
            $table->float('GoogleLat', 10, 8)->nullable();
            $table->float('GoogleLong', 10, 8)->nullable();
            $table->timestamps();
        });

How do I then save a new user with their address using eloquent?

I tried things like $user->address_1 or $user->address->address_1with no luck.

Please sign in or create an account to participate in this conversation.