Skip to content

Instantly share code, notes, and snippets.

@anaxamaxan
Created November 8, 2021 18:47
Show Gist options
  • Save anaxamaxan/c05e1df86e1b4b2208de7e66959f3960 to your computer and use it in GitHub Desktop.
Save anaxamaxan/c05e1df86e1b4b2208de7e66959f3960 to your computer and use it in GitHub Desktop.
Laravel Eloquent Model::whereWithHas() global dynamic scope
<?php
namespace App\Models;
use App\Models\Traits\WithWhereHas;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model as BaseEloquentModel;
abstract class Model extends BaseEloquentModel
{
public function scopeWithWhereHas(Builder $query, string $column, \Closure $conditions): Builder
{
return $query->whereHas($column, $conditions)
->with([$column => $conditions]);
}
}
<?php
namespace App\Models;
use App\Models\Collections\CourseCollection;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* App\Models\ApprovalBoardRequirement
*
*/
class ApprovalBoardRequirement extends Model
{
use SoftDeletes;
/* ... relations, casts, etc ... */
/* ========================================== Affordances ========================================== */
/**
* Return courses that have approval associated with this requirement's board and this requirement
*/
public function getApprovedCourses(): Builder
{
$withApprovals = function($query) {
return $query->where('course_approvals.approval_board_id', $this->approval_board_id)
->where('course_approvals.approval_board_requirement_id', $this->id);
};
return $query = Course::unexpired()
->published()
->withWhereHas('approvals', $withApprovals);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment