1. Home
  2. Laravel
  3. Hasmany

Has many sets a single-to-many relationship between two Models. Use plural form in the name of your function (subitems in this example). This is a good practice as a collection of records will be returned when the method is called. Pass a Model class you want to reference as an argument.

#laravel#model
// Set the relationship in a Model file

class Item extends Model {
    public function subitems() {
        return $this->hasMany(SubItem::class); // Item has many SubItems
    }
}

// Then, in a Controller, you can fetch all SubItems related to the Item like so 
App\Item::first()->subitems;
copy
Full Laravel cheatsheet