Hey Laravel Developers
Starting with Laravel v11.31.0, we have a new build() method available on the DB Facade in Laravel.
This new build() method allows you to generate database connections on the fly in your application code, instead of defining the connections in the database.php config file.
One practical example is when you want the user to provide database connection details so you can import or fetch certain data, such as product information.
Hey Laravel Developers
Spatie's media library is an amazing package that allows us to easily connect media files on our Eloquent Model.
One of the things I was looking out for was eager loading the media files.
Here is the use case for which I needed to do this. Let's say we are showing a list of users in our application along with their avatars, which are connected via the media library package.
The problem was using the getMedia() method was making n+1 queries when used with a loop
So, it was pretty simple to do this. We just had to load the media relationship on our eloquent model.
This is possible because the media morph relationship connects all media files to the model.
Hey Laravel Developers,
What do you think is the difference between the following two code snippets?
In the first snippet, we load multiple relationships on the same line using the load method, and in the other, we load multiple relationships on separate lines.
Hey Laravel Developers
When working with web applications, one of the common validations we deal with involves dates.
Many times, I’ve seen developers use the date validation rule to validate date input fields.
However, I’d urge you to use the date_format validation rule instead.
The reason is that the date_format rule gives clients a clear understanding of the format the API expects for the input.
For example, a client might mistakenly pass a datetime in the request, expecting the timestamps to be stored, but you only store the date in the backend.
What do you think about this? Any opinions? I’d love to discuss it!
Hey Laravel Developers
Let me introduce you to the toggle() method, available for many-to-many relationships in Laravel.
This method’s purpose is to toggle the relationship status of a related model, switching it from an attached to a detached state, or vice versa, based on the current status.
A practical application of this method is creating a single controller for both attaching and detaching relationships.
For example, you can create a single controller to mark or unmark a product as a favourite for the logged-in user.