Support the ongoing development of Laravel.io →
Eloquent Laravel Database
Last updated by @tvbeek 7 months ago.
0
moderator

Hello,

Searching without a relation to your model sounds for me a little bit strange to implement. (Unless you have some validation in your request) Now it is possible to add a search on a not existing column to your query. That will result in an error.

But your question about searching on your relation. You can use the whereHas functions ( see: https://laravel.com/docs/9.x/eloquent-relationships#querying-r... )

It is possible to search the existing of a relation with $builder->has('relation'); or you can search on the existing of a relation with a specific value.

$builder->whereHas('relation', static function (Builder $relationQuery) use ($value) {
    $relationQuery->where('column_on_the_relation',  'LIKE', '%'. strtolower($value) . '%');
});

Small note: I have updated your post to make the code more readable

1

Hello tvbeek,

Thank you for your reply.

$builder->whereHas('relation', static function (Builder $relationQuery) use ($value) {
    $relationQuery->where('column_on_the_relation',  'LIKE', '%'. strtolower($value) . '%');
});

that was the right keyword for my problem

EDIT: But now I have the problem, if I want to filter by semester, for example, I get the following error Call to undefined method App\Models\Document::semester().

my code is as follows

if($builder->whereHas($column)) {
    $builder->whereHas($column, static function (Builder $relationQuery) use ($column, $value) {
        $relationQuery->where($column,  'LIKE', '%'. strtolower($value) . '%');
    });
} else {
    array_push($where, [$column, 'LIKE', Str::lower("%{$value}%")]);
}
Last updated 7 months ago.
0

Sign in to participate in this thread!

Cloudways

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2022 Laravel.io - All rights reserved.