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

Monday, February 28, 2022

[FIXED] Issue with implementing a search functionality with Laravel

 February 28, 2022     eager-loading, eloquent, laravel, mysql, php     No comments   

Issue

I am trying to implement a search feature in a site. A user can specify a search string that could match a product_id, product_name or the product_sku. What I want to implement is a search function that would return all that matches.

What I've come with so far:

 return Product::with(['getProductItem' => fn ($query) => $query->orWhere('itemSkuNumber', '=', $request->search)])
                ->where(
                    'name',
                    $request->has('match') ? '=' : 'like',
                    $request->has('match') ? $request->search : '%' . $request->search . '%'
                )
                ->orWhere('id', '=', $request->search)->get();

This has worked if I specify a product_id or product_name but does not return anything if I provide an sku.


Solution

You should wrap orWheres with another where because it will try to filter all of them.

        Product::with(['getProductItem'])
        ->whereHas('getProductItem', function ($query) use ($request) {
            $query->where(function ($subquery) use ($request) {
                $subquery->where('itemSkuNumber', '=', $request->search);
                //put your orwhere queries in here
            });
        })
        ->get();


Answered By - gguney
  • 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

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 © PHPFixing