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 use Laravel dd() method with less code

Hello, guys! Did you know that you don’t have to wrap your Eloquent query with dd() method, and just simple can add it at the end of the query? See how simple it is. How to use dd() in Laravel What is dd() in Laravel? Dump and Die, or dd(), is a Laravel helper function […]

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 get only specific columns in Eloquent using relationships “with()”

If you have relationships like hasMany or manyToMany in Laravel and you need to extract data from specific columns of your DB table with your Eloquent query, just do it like that: Don’t forget to always use a column with primary key (in the example above it is id column) and not to put spaces […]

How to use conditions in Eloquent relationships

You can use conditions in Eloquent with relationships. For example, we’ve got a Team and its Users. We can define the relationship with the name “admins” which extends the user relation with a condition.