Christian
Christian

Reputation: 501

Laravel Query builder: Take and limit methods

I dont undertand how these methods work, I'm trying to get last records inserted in my db and for this, I need a query builder so I made y consult with something like this:

 $costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->take(1);

The thing is I'm still getting all records inserted, in these methods take or limit I send the paramether of how many i want to get, and my question is. Why does this happen??

And no, I dont want to use the first() or get() methods these dont work when you do server side processing in a datattable

Upvotes: 0

Views: 1113

Answers (3)

Stanley
Stanley

Reputation: 499

Try this

$costo = Costo_promedio::orderBy('created_at','desc')->take(3)->get();

That Will get the last three records from the database assuming that your timestamp is named created_at.

Upvotes: 0

Orkhan Alikhanov
Orkhan Alikhanov

Reputation: 10050

take(1) or limit(1) just adds limit 1 to the query in builder. You need to call get() to fetch the results and it will return a Collection and you can get its only element by calling first() on it.

$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->take(1)->get()->first();

Or you can replace take(1)->get()->first() with just first()

$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->first()

first() will add limit 1 and fetch the results and return the only item that's there

Upvotes: 1

Sand Of Vega
Sand Of Vega

Reputation: 2416

first() is not return Collection. It returns a Model instance. Maybe you are not clear about Collection vs Model instance.

$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->first();

Alternative:

$costo = Costo_promedio::where('producto_nombre_id',$id_prod->id)->latest()->get();

// $costo[0]

Upvotes: 1

Related Questions