How to reduce code duplication with relationships in Laravel

Since Laravel 9.16 we can reduce the code a bit, using withWhereHas() method. It’s time to do some code clean up! See the example below: As Laravel contributor Eusonlito describes: There are a lot of times that we need to load a relationship using with with the same conditions that we use for whereHas. This method simplifies this […]

How to use default Models with relationships in Laravel

As you may know, you can skip checking if your relationship doesn’t exist in Laravel with withDefault method. But did you know that you can also assign attributes to a default Model? See the example below:

How to force eager load in Laravel

You can force your app to eager load in Laravel using this method in the Service Provider. This code will throw an exception if you don’t eager load a relationship (except in production).

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 add changes to Model and its relationships in Laravel

When making changes to a Model and its relations in Laravel, you don’t need to call save() method on each of them. Instead, you just can call push() on the main Model and it will recursively save any changes. by @mattkingshott

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 […]