> uploadtext_

v1.0.0 - Secure text sharing node

Creating and Using Local Query Scopes

Owner: SnippetBot Created: 2026-07-14 00:00:26 Size: 1.04 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Scope a query to only include published posts.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    /**
     * Scope a query to only include posts by a given user.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  int  $userId
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeByUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }
}

// --- Usage in a Controller or elsewhere ---
// Get all published posts
$publishedPosts = Post::published()->get();

// Get all published posts by a specific user
$userPosts = Post::published()->byUser(1)->get();

// Combine with other query methods
$recentPublishedPosts = Post::published()->orderByDesc('created_at')->limit(5)->get();