Home > OS >  Laravel 8 Two Table Where Search
Laravel 8 Two Table Where Search

Time:02-04

My Code;

$posts=Term::where('user_id',$user_id)->where('status',1)->where('type','product')->with('preview','attributes','category','price','options','stock','affiliate')->withCount('reviews');

       if(!empty($request->term)){
            $data= $posts->where('title','LIKE','%'.$request->term.'%');
       }

This my code searches for title from term table. But I want to search from another table without breaking the structure. So Example;

 if(!empty($request->term)){

    $data= $termTABLE->where('title','LIKE','%'.$request->term.'%');
    $data= $stockTABLE->where('code','LIKE','%'.$request->term.'%');
    
}

Since I don't know about Laravel, I couldn't explain it fully. I hope I get help. Thanks.

Good Luck

CodePudding user response:

The below example is not like yours' but you can sort it out according to your need.

For example, if user has a company you can search in the company table like

          $user->where('name', 'LIKE', '%' . $searchPhrase . '%') //Searching in user table
                //Searching in user table
               ->orWhere('email', 'LIKE', '%' . $searchPhrase . '%')
                //Checking if company exist
               ->orWhereHas('company', function ($query) use ($searchPhrase) { 
                    //Searching in company table
                    $query->where('name', 'LIKE', '%' . $searchPhrase . '%'); 
               });

CodePudding user response:

So I think you're trying to filter your relationships? If so that is done by passing a callback to the with() method:

$posts = Post::where('user_id', $user_id);
    ->where('status',1)
    ->where('type','product')
    ->where('title', 'like', '%' . $request->input('term') . '%')
    ->with('preview', 'attributes', 'category', 'price', 'options', 'affiliate')
    ->with([
        'stock' => fn ($q) => $q->where('code', 'like', '%' . $request->input('term') . '%')
    ])
    // optional, see note below
    ->whereHas('stock', fn ($q) => $q->where('code', 'like', '%' . $request->input('term') . '%'))
    ->withCount('reviews');

So we've removed the stock relationship from the list and put it in its own with() call with a callback that will do the filtering on what's returned.

Note there's no need to check if the request field has a value, as LIKE %% will return all records.

If you want to ensure that only posts with the matching relationship are returned, add a whereHas() call that will ensure the desired relationship exists in the first place. To clarify:

  • Post::with('stock') returns all posts with all stocks
  • Post::with('stock', 'some condition') returns all posts with some stocks
  • Post::whereHas('stock', 'some condition') returns some posts with all stocks
  • Post::whereHas('stock', 'some condition')->with('stock', 'some condition') returns some posts with some stocks.
  •  Tags:  
  • Related