Engineering note · Laravel

Use Query Scopes for Reusable Queries

By Published Updated

Laravel

Encapsulate common query logic within model scopes to keep your code DRY (Don't Repeat Yourself). Scopes make your queries reusable and your code more readable.

In your Post model

CODE SAMPLE Code snippet
// In your Post model
class Post extends Model {
    public function scopePopular($query) {
        return $query->where('views', '>', 1000);
    }
}

// Usage
$popularPosts = Post::popular()->get();

More engineering notes

Modify Response with Middleware

Modify or enhance responses using middleware, such as adding headers, manipulating content, or handl...

Minimize Direct Queries in Blade Views

Avoid executing database queries directly within Blade templates. Instead, fetch data in the control...