Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the first model from a hasMany relationship in Laravel

Tags:

Is it possible to create a quick method to return the first model from a one-to-many relationship? Here is my code, from the model file:

public function books() {     return $this->hasMany('App\Models\Book'); }  public function first_book() {     return $this->book()->first(); } 

This is the error I'm getting:

Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints() 

The reason I want to use this is so that I can collect the first record using the with() method, for example:

$authors = Author::with('first_book')->select('*'); 

I'm using these records with Datatables.

like image 619
f7n Avatar asked Jun 13 '17 14:06

f7n


People also ask

What does First () return in Laravel?

I don't know what version of Laravel you were using, but first() doesn't throw an exception if the table doesn't have matching rows, and I know it hasn't since at least Laravel 4.2. It just returns null. It may be that the exception was caused by a different issue with your code.

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.


2 Answers

I might be late but for your future use and for other who want the same output try this one -

// If you need the last one

public function books() {     return $this->hasOne('App\Models\Book')->latest(); } 

// If you need the first entry -

public function books() {         return $this->hasOne('App\Models\Book')->oldest();     } 
like image 99
Keshari Nandan Avatar answered Sep 18 '22 15:09

Keshari Nandan


A relation that can be eager loaded has to return a query. The first() function returns an eloquent object.

The solution is to limit the number of results of this query like so:

public function first_book() {     return $this->books()->take(1); } 

$author->first_book will still be a collection, but it will only contain the first related book in your database.

like image 32
Jerodev Avatar answered Sep 18 '22 15:09

Jerodev