0

I have these 2 linked models: jobs and job_translations. A job have many translations. So in my job model, there is :

/**
 * Get the translations for the job.
 */
public function translations()
{
    return $this->hasMany('App\Models\JobTranslation');
}

In my controller, I want to build a query dynamically like that :

$query = Job::query();
if ($request->has('translation')) {
            $query->translations()->where('external_translation', 'ilike', '%'.$request->translation.'%');
        }

$jobs = $query->paginate(10);

I have this error :

Call to undefined method Illuminate\Database\Eloquent\Builder::translations()

Is it possible to do such a dynamic query with Eloquent?

2 Answers 2

1

Yes, it is possible. What you are looking for is whereHas('translations', $callback) instead of translations():

$query = Job::query();
if ($request->has('translation')) {
    $query->whereHas('translations', function ($query) use ($request) {
        $query->where('external_translation', 'ilike', '%'.$request->translation.'%');
    });
}

$jobs = $query->paginate(10);

Your query can be improved further by using when($condition, $callback) instead of an if:

$jobs = Job::query()
    ->when($request->translation, function ($query, $translation) {
        $query->whereHas('translations', function ($query) use ($translation) {
            $query->where('external_translation', 'ilike', "%{$translation}%");
        });
    })
    ->paginate(10);
Sign up to request clarification or add additional context in comments.

1 Comment

Hello Namoshek. GREAT, it works exactly as expected. You saved my day . Merci beaucoup. Dom
0

the issue you should do eager loading to detected on next chained query like this:

$query = Job::with('translations')->query();

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.