David David - 1 year ago 550
PHP Question

Where ID is NOT equal to the current Product ID being viewed - Laravel 5.2

I'm displaying similar products in my Product Page. I have a query that finds all products with a similar brand_id or cat_id for the product being viewed. My problem is that it also displays the current product being viewed in the similar section. I need to make it so it removes the current product being viewed from the similar products section.

This is the query I have right now. ( The 'id', '!==', $product->id part is not working)

* Show a Product in detail
* @param $product_name
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
public function show($product_name) {

// Find the product by the product name in URL
$product = Product::ProductLocatedAt($product_name);

// Select All from "products" table where the brand_id is = to the current product being viewed with its brand_id, OR where
// the category_id is = to the current product category Id being viewed. This is so we can display similar products for a // particular product being shown.
$similar_product = Product::where('brand_id', '=', $product->brand_id)
->where('id', '!==', $product->id)
->orWhere('cat_id', '=', $product->cat_id)->get();

return view('pages.show_product', compact('product', 'similar_product'));

******** EDIT ********
I'm getting this when using your query method:

Do you know y that might be?

Answer Source

Keep in mind when using OR that Laravel's query builder doesn't add parenthesis by default.


Your query will end up like this:

FROM products
WHERE brand_id = 1
   AND id != 2
   OR cat_id = 3

Because of the OR, the results include the product based on its cat_id.

What you probably want is:

$similar_product = Product::where('id', '!=', $product->id)
    ->where(function ($query) use ($product) {
        $query->where('brand_id', '=', $product->brand_id)
            ->orWhere('cat_id', '=', $product->cat_id);

This will put the OR part inside a set of parenthesis:

FROM products
WHERE id != 2
   AND (brand_id = 1 OR cat_id = 3)

Please keep in mind that, often, MySQL does a bad job at optimizing with OR clauses. If your tables are large, you may want to double check the performance and index usage.