Home > Blockchain >  In Laravel hasMany relationship How to use with and where?
In Laravel hasMany relationship How to use with and where?

Time:07-22

In Job model :

public function jobApplications()
{
return $this->hasMany(JobApplication::class, 'job_id');
}

In JobApplication Model

public function jobs()
{
return $this->belongsTo(Job::class, 'job_id');
}

In job_applications migration

$table->id();
$table->foreignId("job_id")->constrained("jobs");
$table->foreignId("user_id")->constrained("users");
$table->text('remarks')->nullable();
$table->unsignedInteger('status')->default(1);

I need to get all jobs and its job applications where job_applications.status = (user input status) and job_applications.user_id =authenticated users id. How can i get that?
Below is the syntax i tried, which returned undefined variable status

$jobs = Job::where('status',1);
$status =$request->status;

if($status){
$jobs = $jobs->whereHas('jobApplications', function($q){
$q->where('status',$status);
$q->where('user_id',Auth()->user()->id);
});
return $jobs->get();
Can any one sugest a solution?

CodePudding user response:

If you use closer the variabl that is defined outside the closer is not accessible. so you should use it. Like this.

if($status){
   $jobs = $jobs->whereHas('jobApplications', function($q) use($status){
    $q->where('status',$status);
   $q->where('user_id',Auth()->user()->id);
  });

This will remove the error undefined veriable $status.

CodePudding user response:

to use an external variable in closure method you need to pass that variable into method using "use" keyword like

if($status){
   $jobs = $jobs->whereHas('jobApplications', function($q) use ($status) {
   $q->where('status',$status);
   $q->where('user_id',Auth()->user()->id);
});}
return $jobs->get();
  • Related