<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
protonemedia / laravel-eloquent-scope-as-select example snippets
use ProtoneMedia\LaravelEloquentScopeAsSelect\ScopeAsSelect;
public function boot()
{
ScopeAsSelect::addMacro();
// or use a custom method name:
ScopeAsSelect::addMacro('withScopeAsSubQuery');
}
Post::addScopeAsSelect('is_published', function ($query) {
$query->published();
})->get();
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
public function scopePublished($query)
{
return $query->whereNotNull('published_at');
}
public function scopePublishedInCurrentYear($query)
{
return $query->whereYear('published_at', date('Y'));
}
}
Post::addScopeAsSelect('is_published', function ($query) {
$query->published();
});
// is the same as:
Post::addScopeAsSelect('is_published', 'published');
Post::addScopeAsSelect('is_announcement', function ($query) {
$query->ofType('announcement');
});
// is the same as:
Post::addScopeAsSelect('is_announcement', ['ofType' => 'announcement']);