Home > Enterprise >  Laravel Eloquent, where query on child model with if statement
Laravel Eloquent, where query on child model with if statement

Time:09-01

Can someone help me out, I'm trying to do a where query on a Child Model. Everything seems fine when I have a value for the id but it returns nothing when no id is supplied.

My goal is to get all data when no id is supplied and get specific data when id supplied.

Here's my code

Report::with(['project'])
->whereHas('project' function($q) use($programId){ 
   if($programId){
    $q->where('program_id', $programId);
   }
})->get();

Is there a better way to achieve my goal? or I just lack something on the query? Thank you in advance.

CodePudding user response:

You can use when method for this.
The when method only executes the given closure when the first argument is true. If the first argument is false, the closure will not be executed.

Report::with('project')
->when($programId, function ($query) use ($programId) {
   $query->whereHas('project' function($q) use($programId){ 
      $q->where('project.program_id', $programId);
   });
})->get();

CodePudding user response:

So I have a little complex answer for this type of questions where you can create a query and do every logic to it.

// Initialise the model
$query = new Report;

// Start building the query
$query->with('project');

// Check if project Id exists
if ($projectId) {
    return $query->whereHas('project', function ($subQuery) use ($projectId) {
         $subQuery->where('program_id', $programId);
    })->get();
} else {
    return $query->get();
}
  • Related