Created
November 8, 2021 18:47
-
-
Save anaxamaxan/c05e1df86e1b4b2208de7e66959f3960 to your computer and use it in GitHub Desktop.
Laravel Eloquent Model::whereWithHas() global dynamic scope
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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