07 - FirstOrCreate, and Other 2-in-1 Methods
Laravel Eloquent has quite a few "two-in-one" features: do something or do something else. And I will demonstrate a few of them now
We found 13 results for "eloquent methods".
Laravel Eloquent has quite a few "two-in-one" features: do something or do something else. And I will demonstrate a few of them now
Eloquent is a great thing - you can build your query step-by-step and then call get() method. But sometimes it gets a little tricky for more complicated queries - for example, if you have multiple AND-OR conditions and you want to put brackets, how to do it properly?
Eloquent has one less-known function called withCount(): it helps to get the amount of related records inside of the main object. It also works with two layers deep, inside of hasManyThrough relations. Let's take a look.
Many of us are used to write conditional Eloquent queries with "if-else". What if I told you there's a (much) better way? Easily readable and more Laravel-ish.
Quick video, comparing two Laravel queries that perform almost the same task - querying by relationship. WhereHas() or join()?
Recently I've found a small detail in Laravel documentation which I want to share with you. Apparently, it's possible to filter pivot tables additionally, if needed. Let me show you how.
Let's say you want to filter out entries created today. You have a timestamp field created_at, right? How do you filter the DATE only from that timestamp? Apparently, Taylor thought about it.
A very convenient way to populate dropdown options with Eloquent is to use lists() function. But it doesn't work out of the box with "Append" fields, also called "Accessors". Here's a small trick to make it work.
From time to time I write short tips about Laravel, and one of the most popular topics is Eloquent. It has so many "hidden" or poorly documented functionality, one of those is filtering parents by whether they have or don't have children. Let's see an example.
Some Laravel functions are not mentioned or emphasized in the official docs, especially if they change from version to version. One of these examples is simple where() in Eloquent - what do you think, does it compare in a "strict" or "loose" way?
There's one really neat Laravel Eloquent function which, from my experience, a lot of developers don't know. How do we write WHERE clauses on Eloquent queries?
Let's imagine a simple situation - you need to write an Eloquent query and order the result by the difference of two columns. Or some other calculation. Time to apply a raw query!