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();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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.
@madsynn You have to set your relationship.
Documentation: https://laravel.com/docs/7.x/eloquent-relationships#many-to-many
Staff model
public function categories()
{
return $this->belongsToMany('App\StaffCategory');
}
Then this will be work
$sales = Staff::whereHas('categories', function ($query) {
$query->where('name', 'sales');
})->where('published', true)->get();
Please or to participate in this conversation.