For getting every new tutorial link Please join our telegram group

Part 3 laravel hasMany relationship get only one record by Has One Of Many

In this laravel eloquent we will discuss how to get single data record in hasMany() or one to many relationship. How to use conditions for getting single record in hasMany relationship. In simple words we will discuss these methods on hasMany relationship in model latestOfMany(), oldestOfMany() and ofMany()

Laravel hasMany() relationship use these methods

  1. latestOfMany()
  2. oldestOfMany()
  3. ofMany()

Laravel hasMany() relationship latestOfMany() method

Laravel hasMany() relationship get many rows from relation table but some time we want to get a single row from these related records also called has one of many relationship then use some methods. One of them is latestOfMany() method. latestOfMany() method use when we get latest or new record which is related to main model. In our example if we get last salary of employee from salarys table with main model Employee then use latestOfMany() method with hasMany() method.

Employee model
public function latestSalary() {
    return $this->hasOne(Salary::class)->latestOfMany();
}

Laravel hasMany() relationship oldestOfMany() method

oldestOfMany() method work same as latestOfMany() method. Difference between them oldestOfMany() method get oldest data which are related to main model. these methods find old or new data according to primary key which must sortable. Example of oldestOfMany method

Employee model
public function latestSalary() {
    return $this->hasOne(Salary::class)->latestOfMany();
}

Laravel hasMany() relationship ofMany() method

Laravel oldestOfMany() and latestOfMany() method work according to primary column sorting value but if we want sort hasMany() data by different column use ofMany() method where pass first attribute column name and second is min or max value. these are get related model selected column minmum or maximum values. For example we want get maximum or minimum salary of a employee.

Employee model
public function largestSalary() {
    return $this->hasOne(Salary::class)->ofMany('amount', 'max');
}

public function lowestSalary() {
  return $this->hasOne(Salary::class)->ofMany('amount', 'min');
}

You read this tutorial on advanced web tutorial by anmol sharma. Here we provide laravel beginners to advanced tutorial.

php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Related tutorial links