greener greener - 3 months ago 7
PHP Question

Getting and updating the latest related model in Eloquent

I've been following this article and set myself up with these models:

class Topic extends Node{
public function section(){
return $this->hasOne('App\Section')->latest();
}
public function allSections(){
return $this->hasMany('App\Section');
}
}
class Section extends Model
{
public function topic(){
return $this->belongsTo('App\Topic');
}
}


When I query the data using eager loading, the result is as expected, which is that for each Topic, only one Section is returned (the latest).

Topic::with('section')
->where('id', $id)
->get(); //returns one section for each topic


However, when I query like this:

$section = $topic->section()->get(); //returns many


it returns all the Sections. Similarly, when I try to
update
, it updates all the sections:

$topic->section()->update([
'content' => $input['section']
]); // updates many


How do I get it to
update
only the latest/intended one?

Answer

You do it wrong. Try this:

$topic->section->update([
   'content'   => $input['section']
]);