How to use whereColumn() method in Laravel

Quick tip: you can use a pretty handy Eloquent method called whereColumn() to verify if columns are equal. For example, you can find posts that have been updated or posts which have the same title and slug. Here is the code: Read more in the official documentation here.

How to filter by NULL in Eloquent Collections Laravel

Eloquent collections are one of the most powerful tools in the Laravel toolbox. They give you a fluent, convenient wrapper for complex SQL queries. You can chain together different conditions to create complex queries and then call methods on the resulting collection to fetch your data. And here comes the trap. For example, you filter […]

How to get IDs from a collection in Laravel

You can always retrieve IDs from Eloquent Collection in Laravel with the built-in method modelKeys: As the official documentation says, the modelKeys method returns the primary keys for all models in the collection

How to query belongsToMany relationships in Laravel

Suppose we have Posts which belong to many different Categories. For this purpose we make three DB tables: posts (id, title), categories (id, name), and an intermediate one (posts_categories, with columns post_id and category_id). The Post Model should be: The Category Controller: You can also return posts collection with dynamic parameters:

How to flatten a collection in Laravel

Here is a cool trick with the flatten method, which can convert your multi-dimensional Laravel collection into a flattened (single dimension) one. See the code below:

How to check if a collection is not empty in Laravel

You may ask, why the expression !empty($collection) fails to work (could be a controller or a blade view). The answer is that you have to check the empty state of the collection a bit differently in Laravel. Here is the code: I would prefer the last method as the most self-explanatory one, and it doesn’t […]

Higher order messages in Laravel

Hello friends! In Laravel, you can utilize the shortcut for “higher order messages” that come with collections. This is extremely useful for performing common actions. See the code below: