Laravel search from translation table and relationship

I have three tables: products, products_translations and products_attributes.
I’m also using laravel-translatable.

So far I can search by the name of the product with the following code of my controller:

public function search(Request $request) {
  $search = $request->input('search');
  $products = Product::whereTranslationLike('name', '%' . $search . '%')->with('attributes')->get();

  return view('search', compact('products'));

In addition I need to display result from the relationship as well. In my case the SKU is part of the products_attributes, which is relationship of the product model.

This is my code of the Product model:

public function attributes(){
    return $this->hasMany(ProductAttribute::class, 'product_id')->orderBy('id', 'asc');

When I dump the product with this code in my view:
{{ dump($product) }}

I can see the relationship but how can I search with SKU field as well?

EDIT: Here’s the view part of the search form:

<div class="form-search">
  <form action="{{ route('search') }}" method="post">
    <div class="input-group">
      <input type="text" class="form-control" name="search" placeholder="{{ __('t.searchHere') }}..." required>
      <span class="input-group-btn">
        <button type="submit" class="btn btn-default" aria-label="Submit">
            <i class="fas fa-search"></i>


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try something like :

public function search(Request $request) {

     $search = $request->input('search');

     $products = Product::with('attributes')->orWhereHas('attributes', function (Builder $q) use ($search) {
         $q->where('YourFieldNameSKU', $search);
     })->orWhereTranslationLike('name', '%' . $search . '%')

     return view('search', compact('products'));

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x