Premium
PHP Snippets.

Curated list of production-ready PHP scripts and coding solutions.

PHP

Get Latest or Oldest Related Model with Eloquent `ofMany`

Learn how to use Laravel Eloquent's `ofMany` method to efficiently retrieve a single latest or oldest related model directly, avoiding collection loading and simplifying complex queries.

View Snippet →
PHP

Implementing Eloquent Soft Deletes

Learn how to implement soft deletes in Laravel Eloquent models, allowing you to "delete" records without permanently removing them from your database.

View Snippet →
PHP

Implementing Eloquent Polymorphic Relationships

Understand and implement polymorphic relationships in Laravel Eloquent, allowing a single model to belong to multiple different models on a single association.

View Snippet →
PHP

Customizing Eloquent Attributes with Mutators and Accessors

Learn to use Eloquent mutators to modify data before saving and accessors to format data when retrieving, enhancing model attribute handling.

View Snippet →
PHP

Implementing Eloquent Global Scopes

Apply automatic query constraints across all queries for a model using Eloquent global scopes, perfect for filtering tenant data or active records.

View Snippet →
PHP

Querying JSON Columns in Laravel Eloquent

Discover how to efficiently query and update JSON columns in your database using Laravel Eloquent's powerful built-in functionalities.

View Snippet →
PHP

Create Reusable Query Filters with Eloquent Local Scopes

Learn how to define and utilize Eloquent local scopes to create reusable query constraints, making your Laravel database queries cleaner and more modular for filtering data.

View Snippet →
PHP

Automatically Convert Eloquent Model Attributes with Type Casting

Discover how Eloquent attribute casting automatically converts model attributes to common PHP data types like arrays, booleans, dates, or custom types, simplifying data handling.

View Snippet →
PHP

Filter Parent Records Based on Related Model Conditions with `whereHas`

Learn to use Eloquent's `whereHas` method to filter parent models based on the existence and conditions of their related models, improving complex data retrieval.

View Snippet →
PHP

Process Large Datasets Efficiently Using Eloquent Query Chunking

Optimize memory usage when iterating through large result sets in Laravel with Eloquent's `chunk` method, preventing memory exhaustion and improving performance.

View Snippet →
PHP

Automate Logic on Model Events with Eloquent Observers

Implement Eloquent Observers to centralize and automate logic that needs to run when models are created, updated, deleted, or other lifecycle events occur in Laravel.

View Snippet →
PHP

Efficiently Load Relationships with Eloquent Eager Loading

Prevent N+1 query problems in Laravel Eloquent by using eager loading (with method) to fetch related models in a single query, significantly improving performance.

View Snippet →