eLeonZ
eLeonZ

Reputation: 37

Laravel 5 saving and updating models with relationship

First thank for watch my question and sorry for my poor english.

I have two models :

User Model with the next relationship:

public function datosAlumno()
{
    return $this->hasOne('sj\Models\DatosAlumno','alumno_id');
}

and DatosAlumno model :

public function alumno(){
    return $this->belongsTo('sj\Models\User','alumno_id');
}

if I print with dd(\Request::all()) :

array:16 [▼
    "_method" => "PUT"
    "_token" => "vnQp4msoo8UHGan5m4v8VYvX1kKYx8HnbhqaywZH"
    "rut" => "111111111111"
    "nombre" => "AAAAAAAAAA"
    "apellido_paterno" => "BBBBBBBBBBB"
    "apellido_materno" => "CCCCCCCCCCCC"
    "sexo" => "masculino"
    "comuna_id" => "13"
    "direccion" => "RRRRRRRRRRRRRRRRRRRRRR"
    "telefono_fijo" => "14876955"
    "telefono_movil" => "3333333333"
    "fecha_nacimiento" => "2000-11-03"
    "email" => "[email protected]"
    "datosAlumno" => array:1 [▼
        "apoderado_id" => "37"
    ]
    "password" => ""
    "password_confirmation" => ""
]

I'm trying save or update "datosAlumno" but when I use save, push or update the field doesn't change in the database

public function update($id)
{
    $user = User::with('datosAlumno')->find($id);
    $user->fill(\Request::all());
    $user->push();
}

If I do dd($user->datosAlumno) after to fill with \Request::all() I get this :

DatosAlumno {#297 ▼
    #table: "datos_alumno"
    #fillable: array:2 [▼
        0 => "alumno_id"
        1 => "apoderado_id"
    ]
    #connection: null
    #primaryKey: "id"
    #perPage: 15
    +incrementing: true
    +timestamps: true
    #attributes: array:6 [▼
        "id" => 1
         "alumno_id" => 97
         "apoderado_id" => 15
         "deleted_at" => null
         "created_at" => "0000-00-00 00:00:00"
         "updated_at" => "0000-00-00 00:00:00"
    ]
    #original: array:6 [▼
        "id" => 1
        "alumno_id" => 97
        "apoderado_id" => 15
        "deleted_at" => null
        "created_at" => "0000-00-00 00:00:00"
        "updated_at" => "0000-00-00 00:00:00"
    ]
    #relations: []
    #hidden: []
    #visible: []
    #appends: []
    #guarded: array:1 [▶]
    #dates: []
    #casts: []
    #touches: []
    #observables: []
    #with: []
    #morphClass: null
    +exists: true
}

Upvotes: 1

Views: 7437

Answers (1)

Sh1d0w
Sh1d0w

Reputation: 9520

You have to set the data to the DatosAlumno model (hasOne relation) before you push to database. Currently you set the data only to the user model. So this will work:

public function update($id)
{
    $user = User::with('datosAlumno')->find($id);
    $user->fill(\Request::all());
    $user->datosAlumno->fill(\Request::get('datosAlumno'));
    $user->push();
}

By the way it is a good practice to ALWAYS write your function and variable names in English. This way the code is more readable and easy to understand for anyone that will work on this code after you.

Upvotes: 5

Related Questions