PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

[FIXED] How to search into relation table?

 November 15, 2022     eloquent, laravel, laravel-6     No comments   

Issue

I have two tables, first is Category table that has id and name columns.

Second table is Product that has id, category_id and name columns.

public function category() {
    return $this->belongsTo(Category::class);
}

My question is how to search product's name, and it's category name in one Eloquent or DB query?


I tried the below code, it work for products name but when I search the category name it returns nothing.

$searchText = $request->input('search');
Product::query()
    ->where(function($query) use($searchText){
        if($searchText) {
            $query->where('name', 'LIKE', '%'.$searchText.'%')
                ->orWhere(function($query2) use($searchText) {
                    $query2->with(['category' => function($query3) use ($searchText){
                        $query3->where('name', 'like', '%'.$searchText.'%');
                    }]);
                });
        }
    })
    ->paginate(8);

And also, I would like to ask which is best to use this scenario Eloquent or DB?


Solution

$query = Product::query()->with('category')
            ->where(function($query) use($request) {
        if ($request->input('search')) {
            $search_text = $request->input('search');
            $query->where('name', 'Like', '%' . $search_text . '%')
            ->orWhereHas('category', function ($query2)use($search_text) {
                $query2->where('name', 'Like', '%' . $search_text . '%');
            });
        }
    });

    $query1 = $query->paginate(8);

Hope fully it will help to you easily.



Answered By - Ankita Dobariya
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,210,837

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing