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

Jarjis's avatar

Laravel Relationship Query Did not work

I have two table 1. applications 2. users --applications-- table contains id,user_id,categroy,status | I want to filter applications table user name and also application column name

	 $applications = Application::with(['user'=>function($query) use ($request){
            $query->where('name','like','%'.$request->name.'%');
        }])->when($request->category,function ($query,$category){
            return $query->where('category',$category);
        })->paginate(10)->appends([
            'name'=>$request->name,
            'category'=>$request->category
        ]);

with relatinship query didn't work how to solve this issue?

  • Thanks
0 likes
23 replies
vincent15000's avatar

Do you have an error ? Have you declared the relationship in the application model ?

Have you tried with whereHas() instead of with() ?

vincent15000's avatar

@Jarjis Can you try only this part of the query ?

$applications = Application::whereHas(['user'=>function($query) use ($request) {
    $query->where('name', 'like' ,'%'.$request->name.'%');
}])->get();
vincent15000's avatar

@Jarjis If it doesn't work, you can also reverse the query like this.

$users = User::with('applications')->where('name', 'like', '%'.$request->name.'%')->get();

And then you can access the applications from each user.

vincent15000's avatar

@Jarjis Let me have a look by testing directly on an app and I come back with more precisions in a few minutes ;).

1 like
vincent15000's avatar

@Jarjis I have it ... you have to use whereHas() but with this syntax.

$applications = Application::whereHas('user' => function($query) use ($request) {
    $query->where('name', 'like' ,'%'.$request->name.'%');
})->get();

You have to not use [ ... ].

whereHas([ ... ]) has to be changed to whereHas(...)

vincent15000's avatar

@Jarjis Great ... so you can close the post by setting the best answer to the answer that allowed you to solve your problem ? ;)

iftekhs's avatar

Can you explain a bit? as far as I understood the application table contains 1 user ie belongs to a user right? so why would you even filter that user? Do you want to get all the application belongs to a user with the name $request->name?

1 like
vincent15000's avatar

@iftekhs No he wants to retrieve all applications that belong to a user for which the name is like $request->name, the filter can filter for several users at a time.

vincent15000's avatar

@iftekhs I think that he wants the list of the applications, but only the application for which the user name is like $request->name. Example : $request->name = 'Sou so the applications for which the user name is Soulier and Souquier will be retrieved.

1 like

Please or to participate in this conversation.