Premium
PHP Snippets.

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

PHP

Format Model Attributes with Eloquent Accessors & Mutators

Learn to transform Eloquent model attributes on retrieval (accessor) or before saving (mutator) for cleaner data handling, presentation, and data integrity.

View Snippet →
PHP

Leverage Eloquent Model Events for Lifecycle Hooks

Discover how to use Eloquent model events (e.g., creating, updated, deleted) to execute custom logic during a model's lifecycle, like sending notifications or logging.

View Snippet →
PHP

Query JSON Columns in Laravel Eloquent

Efficiently query and filter Eloquent models based on data stored within JSON-type columns in your database tables using Laravel's powerful methods.

View Snippet →
PHP

Integrate Raw SQL Expressions in Eloquent Queries

Learn to use `DB::raw` to embed complex SQL functions or subqueries directly into your Eloquent builder statements for advanced database interactions.

View Snippet →
PHP

Efficiently Paginate Eloquent Query Results

Implement pagination for your Eloquent models to present large datasets in manageable chunks, improving performance, loading times, and user experience.

View Snippet →
PHP

Implementing Soft Deletes in Laravel Eloquent

Learn how to implement soft deletes in your Laravel Eloquent models, allowing you to 'archive' records instead of permanently deleting them, with easy restoration.

View Snippet →
PHP

Filtering Eloquent Models by Related Model Existence

Discover how to filter parent models based on the existence or specific conditions of their related child models using Eloquent's `whereHas` and `has` methods.

View Snippet →
PHP

Efficient Data Transformation with Eloquent Collections

Leverage powerful methods like `pluck`, `map`, and `filter` on Eloquent collections to efficiently transform, filter, and extract specific data from query results.

View Snippet →
PHP

Efficient Relationship Aggregates with Eloquent `withCount`

Learn to efficiently retrieve counts of related models for a collection of parent models using Eloquent's `withCount` method, avoiding N+1 query problems.

View Snippet →
PHP

Optimize Eloquent Queries with Eager Loading

Prevent N+1 query problems in Laravel Eloquent by efficiently loading relationships using eager loading (`with()` method), significantly boosting application performance.

View Snippet →
PHP

Apply Global Query Scopes to Eloquent Models

Automate common query constraints across all instances of an Eloquent model using global scopes, ensuring consistent data filtering and DRY code.

View Snippet →
PHP

Create Reusable Local Query Scopes in Eloquent

Organize and reuse common query logic within your Laravel Eloquent models using local scopes for cleaner, more expressive, and maintainable code.

View Snippet →