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

Imadev's avatar

eloquent query relations

I have a Job table that hasMany JobData i want to query Job::where('is_active', true)->JobData('title', 'LIKE', $query) (this is just pseudo code)

this is the code I wrote, but the problem is that it gets also Job items that don't satisfy the condition

$jobs = Job::where('is_active', 1)
    ->whereHas(['data' => function($query) use($keyword) {
        $query->where('status', 'pending')
            ->where('title', 'LIKE', "%{$keyword}%");
        }])->get();

the only way I could get the right data I want is with query builder but I can't use the relations in the Model

0 likes
7 replies
elieandraos's avatar

what is the jobData relation name in your job Model ?

elieandraos's avatar

@imadev I think you have a syntax error in your whereHas parameters. It should be (relationName, function()) not array.

$jobs = Job::where('is_active', 1)
    ->whereHas('data' , function($query) use($keyword) {
        $query->where('status', 'pending')
            ->where('title', 'LIKE', "%{$keyword}%");
        })->get();
elieandraos's avatar
Level 6

@imadev This is from the Laravel docs, no array as param:

// Retrieve posts with at least one comment containing words like foo%...
$posts = App\Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'foo%');
})->get();
Dalma's avatar

I'm not sure what your { and } are doing to your query?

"%{$keyword}%"

my code uses

"%$keyword%"
Imadev's avatar

thank you, it works now. Honestly I don't know where I got the the array syntax from, I think it's the 1AM effect

Please or to participate in this conversation.