Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

madsynn's avatar

Help with Query please

I have 2 cruds staff, and staff_categories.

I need to query each category and check if published and output them.

Staff table:

        Schema::create('staff', function (Blueprint $table) {
            $table->increments('id');
            $table->date('startdate')->nullable();
            $table->string('name')->nullable();
            $table->string('job_title')->nullable();
            $table->longText('short_intro')->nullable();
            $table->longText('bio')->nullable();
            $table->boolean('published')->default(0)->nullable();
            $table->string('slug')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });

Staff Categories table

        Schema::create('staff_categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->longText('description')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });

**Staff Category Pivot **

        Schema::create('staff_staff_category', function (Blueprint $table) {
            $table->unsignedInteger('staff_id');
            $table->foreign('staff_id')->references('id')->on('staff')->onDelete('cascade');
            $table->unsignedInteger('staff_category_id');
            $table->foreign('staff_category_id')->references('id')->on('staff_categories')->onDelete('cascade');
        });

Any help would be appreciated.

so example of what I'm trying to do is this.

sales = staff-> staff_category -> where ( staff_category == sales) ->where (staff->published == true) ->get

As you can see I'm not sure how to get this to come back.

Another way would be to loop through the staff that are published for each staff category.

Thank you in advance.

0 likes
5 replies
tykus's avatar

I believe this is what you are asking for:

$sales = Staff::whereHas('staff_category', function (Builder $builder) {
	$builder->where('staff_category', 'sales');
})->where('published', true)->get();
madsynn's avatar

@tykus thank you for you help but It is still not working. I tried the code above and also tried these 2 versions with no luck.

        $sales = Staff::whereHas('staff_categories', function (Builder $builder) {
            $builder->where('name', 'sales');
        })->where('published', true)->get();
        
        $sales = Staff::whereHas('staff_categories', function (Builder $builder) {
            $builder->where('staff_category_id', '2');
        })->where('published', true)->get();
madsynn's avatar

My Staff Relationship is already many to many. Here is what I have.

    public function staff_categories()
    {
        return $this->belongsToMany(StaffCategory::class);
    }

Please or to participate in this conversation.