Home > OS >  Searching with multiple tables in laravel
Searching with multiple tables in laravel

Time:10-02

I have this search query

 $products = Product::query()
            ->where('name', 'LIKE', "%{$search}%")
            ->orWhere('slug', 'LIKE', "%{$search_any}%")
            ->where('status', 'Active')
            ->get();

i have user table which stores the user who listed the product and its relation is as follows

Product Model:

  public function user()
    {
        return $this->belongsTo(User::class);
    }

I have one field type in user table, i want if user enters search string matches type also then also all the products added by them should be returned i was trying this code but how can i combine both the queries

 $products = Product::query()
                ->where('name', 'LIKE', "%{$search}%")
                ->orWhere('slug', 'LIKE', "%{$search_any}%")
                ->where('status', 'Active')
                ->get();
 $productsAddedByUser = User::where('type', 'LIKE', "%{$search_any}%")->get();
// saved $productsAddedByUser result in this array $userIdarray
$productnew = Product::whereIn('user_id', $userIdarray)->get();

I want to combine both the results of $productnew and $products

CodePudding user response:

At first save result in $userIdarray, then in products query:

$userIdarray = User::where('type', 'LIKE', "%{$search_any}%")->pluck('id');

$products = Product::query()
    ->where(
        fn($query) => $query->where('name', 'LIKE', "%{$search}%")
            ->orWhere('slug', 'LIKE', "%{$search_any}%")
    )   
    ->where('status', 'Active')
    ->when(count($userIdarray), fn($query) => $query->whereIn('user_id', $userIdarray))        
    ->get();
  • Related