Comparing Eloquent's get, cursor, chunk, and lazy methods

2023-07-27 #laravel #eloquent / janostlund.com

A short & sweet overview of get(), cursor(), chunk(), and lazy() to retrieve models from the database. It's a tradeoff between speed and memory usage.


Eloquent findOrFail caveats

2021-11-23 #laravel #eloquent

I use Model::findOrFail a lot in Laravel. Recently, I realized it's not always the best option.

Read more


Tim MacDonald on HasOne relationships in Laravel

2021-03-30 #laravel #eloquent / timacdonald.me

I've used HasOne relationships for 1:1 relationships, but those are rare. I haven't considered using them to scope down relationships, like having one default payment method in a set of n methods.

<?php
 
class User extends Model
{
public function paymentMethods(): HasMany
{
return $this->hasMany(PaymentMethod::class);
}
 
public function defaultPaymentMethod(): ?HasOne
{
return $this->hasOne(PaymentMethod::class)
->whereDefault();
}
}
 
$user->defaultPaymentMethod;

After reading Tim's post, I have a feeling there are some places where I needed this but didn't think of it at the time…