greener greener -4 years ago 120
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).

->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
, it updates all the sections:

'content' => $input['section']
]); // updates many

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

Answer Source

You do it wrong. Try this:

   'content'   => $input['section']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download