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

ayech0x2's avatar

Laravel where condition on a relationship pivot

Hello, i have three tables named passages, statuses and passage_status, so each time a passage's status is changed i attach a new status_id within the table passage_status, so like that i keep like an historic for a passage i mean history of its statuses.

I made this function inside my passage model to get the current status for each one:

public function getCurrentStatus()
  {
    return  $this->statuses()->orderBy('pivot_created_at', 'DESC')->first();
  }

And it's working just fine.

But the problem when i want to filter passages by their current status! Here an example:

public function index(Request $request){
 $statuses = $request->query('statuses');
 Passages:when($statuses, function($query){
  $query->whereHas('statuses', function(Builder $q) use($statuses){
    // What i can do here!
   );				
 })->paginate(8);
}

Do i have to use a query builder with join? But i think using eloquent is su much better i mean for me. Here is an example of the use case.

Let's suppose i have 3 statuses

[
  [
  "id":1,
  "name" => "Waiting",
  ],
[
  "id":2,
  "name" => "Accepted",
  ],
[
  "id":3,
  "name" => "Rejected",
  ],
]

And i'll use a query in this way, http://localhost:8000/passages?statuses=2,3 How can i get passages which their current statuses are with ids 2 and 3?

Thank you in advance.

0 likes
0 replies

Please or to participate in this conversation.