-1

i have at least 8 components have same relation with course model i want to un return this component if this course is hidden

i tried to make it in global scope but still need to do in all these component's model whereHas and with how can i do these in scope in which model? i don't want to repeat these relation in all component maybe once in maybe Global Scope or something like that

Note: i worked with laravel 5.8 i must repeat this in all components like material

$callQuery=function($q) use ($request){
            if(!$request->user()->can('course/show-hidden-courses'))
                $q->where('show',1);
        };
        // $material = $materials_query->with(['lesson','course.attachment'])->whereIn('lesson_id',$lessons);
        $material = $materials_query->whereHas('course',$callQuery)->with(['lesson','course' => $callQuery]);

1 Answers1

0

I am not sure, if I understood your issue well. But, if you are looking for using the same whereHas everywhere. You can just create a scope in your model, basically like:

public function scopeCourse($query){
    $query->whereHas('course', function ($q){
        $q->where('show', 1);
    });
}

And andywhere you like to have this filter, you can just query like:

$materials_query->course()->with([...]);

Besides, if you want to enforce it everywhere, you can just create a Global Scope in for example; App\Model\Scope with the bellow code:

<?php

namespace App\Model\Scope;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class CourseScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        return $builder->whereHas('course', function ($q){
            $q->where('show', 1);
        });
    }
}

And then in your model, you can just:

protected static function boot()
{
    parent::boot();
    static::addGlobalScope(new CourseScope);
}

And then, you can just write your query like:

$materials_query->with([...]);

The scope will be automatically enforced without actually calling the scope, in our case course(). There will be times that you won't need the enforce, so you can call like:

$materials_query->withoutGlobalScope();
Akmal Arzhang
  • 357
  • 4
  • 14