I'm updating a Rental that belongsTo a Location, and I can fill and persist the Rental data, but when I fill the location relationship data retrieved through eager loading if I try to save(), update(), or push(); It isn't persisted to the database. According to the docs push() should work as it apparently persists relationships.
Update Action
public function update($id, RentalUpdateRequest $request)
{
// Eager load the rental with relationships
$Rental = Rental::with('location')->find($id);
// Retrieve rental data from request, and fill
$requestData = $request->only('stall', 'level', 'description');
$Rental->fill($requestData);
// Retrieve rental location data from request, and fill
$requestData = $request->only(
'location.street_address',
'location.city',
'location.province',
'location.country',
'location.postal_code'
);
$Rental->location->fill($requestData);
// Persist rental to database, as well as all relationships
$Rental->update();
// Return rental data for capture by AngularJS interceptor
return response()->json([
'rental' => $Rental,
'action' => 'rental_updated',
'message' => trans('rental.updated')
]);
}
Payload and Eager Loaded Data is Formatted the Same Way
Original rental loaded in the client
rental:
description: "This is a rental."
id: 1
level: "7"
location:
city: "Victoria"
country: "Canada"
id: 11
postal_code: "V8T 2L5"
province: "British Columbia"
street_address: "180 Blanshard Dr."
region_id: 1
rental_location_id: 11
stall: "7"
user_id: 1
If the Payload is:
rental:
description: "This is a rental."
id: 1
level: "9" <-- Changed
location:
city: "asdf" <-- Changed
country: "asdf" <-- Changed
id: 11
postal_code: "V8T 2L5"
province: "asdf" <-- Changed
street_address: "180 Blanshard Dr."
region_id: 1
rental_location_id: 11
stall: "7"
user_id: 1
Response after Save(), Update(), or Push()
rental:
description: "This is a rental."
id: 1
level: "9" <-- Persisted
location:
city: "Victoria" <-- NOT Persisted
country: "Canada" <-- NOT Persisted
id: 11
postal_code: "V8T 2L5"
province: "British Columbia" <-- NOT Persisted
street_address: "180 Blanshard Dr."
region_id: 1
rental_location_id: 11
stall: "7"
user_id: 1
Appears that in Laravel 5.1 push() is being dropped from the API, no longer in 5.1 docs, but save() and update() don't work either, any suggestions?
I've run into this several times now, where I try to set attributes of a eagerly loaded relationship, but only the top level key:value pairs are persisted, and the child relationship pairs are not. The only way around this appears to be to grab the location separately and save(), but what is the point of eager loading like this if I can't save the relationship, and have to make another request to the DB.