0

I'm working on a project in Laravel 6.2. I've two models.

  1. Job
  2. Company

What i want to do is to get all the jobs where the job title matches something and the company city is equal to something. The problem is, it's getting all the job with the companies but if i specify the wrong company city, it still gets the records. In short the condition inside the with not working. What i've done so far:

Model > Job.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Job extends Model
{
    // user
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    // company
    public function company()
    {
        return $this->belongsTo('App\Company');
    }
}

Model > Company.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    // user
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    // job
    public function job()
    {
        return $this->hasMany('App\Job');
    }
}

JobController > search

public function search(Request $request)
{
     $jobs = Job::where('title', 'like', '%' . $request->q . '%')
               ->with(['company' => function($q) use ($request) {
                    $q->where('city', $request->city);
                }])
                ->get();


     return view('jobs.view')->withJobs($jobs);
}
1
  • Hello, in your condition where after you have to ` ->get ();` Commented Mar 19, 2020 at 7:55

2 Answers 2

1

Try the below funtion:

public function search(Request $request)
{
     $jobs = Job::where('title', 'like', '%' . $request->q . '%')
               ->with(['company'])
               ->whereHas('company',function($q) use ($request) {
                    $q->where('city', $request->city);
                })
                ->get();


     return view('jobs.view')->withJobs($jobs);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Your answer's code working even if i remove the ->with(['company']) part. Why ?
->with(['company']) will just select the company relation,whereHas will filter on company's city. if you want company detail then you can use "with(['company'])",if you don't then you can remove that part.
company details are still available if i remove that part
0

in your controller!

public function search(Request $request)
{
   $jobs = Job::where('title', 'like', '%' . $request->q . '%')
           ->with(['company' => function($q) use ($request) {
                $q->where('city', $request->city)->get();
            }])
            ->get();


   return view('jobs.view')->withJobs($jobs);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.