Home » Php » php – related products in single product page with pivot table in laravel 5.8

php – related products in single product page with pivot table in laravel 5.8

Posted by: admin February 25, 2020 Leave a comment

Questions:

I try to make Related_Products in product single page I want to show other products have same category id with pivot table product_categories(product_id , category_id) I tried a lot of code but I can’t do that

Help please how can I do that? thank you very much.

product repository:

<?php

namespace App\Repositories;

use App\Models\Product;
use App\Traits\UploadAble;
use Illuminate\Http\UploadedFile;
use App\Contracts\ProductContract;
use Illuminate\Database\QueryException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Doctrine\Instantiator\Exception\InvalidArgumentException;

/**
 * Class ProductRepository
 *
 * @package \App\Repositories
 */
class ProductRepository extends BaseRepository implements ProductContract
{
    use UploadAble;

    /**
     * ProductRepository constructor.
     * @param Product $model
     */
    public function __construct(Product $model)
    {
        parent::__construct($model);
        $this->model = $model;
    }

    /**
     * @param string $order
     * @param string $sort
     * @param array $columns
     * @return mixed
     */
    public function listProducts(string $order = 'id', string $sort = 'desc', array $columns = ['*'])
    {
        return $this->all($columns, $order, $sort);
    }

    /**
     * @param int $id
     * @return mixed
     * @throws ModelNotFoundException
     */
    public function findProductById(int $id)
    {
        try {
            return $this->findOneOrFail($id);

        } catch (ModelNotFoundException $e) {

            throw new ModelNotFoundException($e);
        }

    }

    /**
     * @param array $params
     * @return Product|mixed
     */
    public function createProduct(array $params)
    {
        try {
            $collection = collect($params);

            $featured = $collection->has('featured') ? 1 : 0;
            $status = $collection->has('status') ? 1 : 0;

            $merge = $collection->merge(compact('status', 'featured'));

            $product = new Product($merge->all());

            $product->save();

            if ($collection->has('categories')) {
                $product->categories()->sync($params['categories']);
            }
            return $product;

        } catch (QueryException $exception) {
            throw new InvalidArgumentException($exception->getMessage());
        }
    }

    /**
     * @param array $params
     * @return mixed
     */
    public function updateProduct(array $params)
    {
        $product = $this->findProductById($params['product_id']);

        $collection = collect($params)->except('_token');

        $featured = $collection->has('featured') ? 1 : 0;
        $status = $collection->has('status') ? 1 : 0;

        $merge = $collection->merge(compact('status', 'featured'));

        $product->update($merge->all());

        if ($collection->has('categories')) {
            $product->categories()->sync($params['categories']);
        }

        return $product;
    }

    /**
     * @param $id
     * @return bool|mixed
     */
    public function deleteProduct($id)
    {
        $product = $this->findProductById($id);

        $product->delete();

        return $product;
    }

    /**
     * @param $slug
     * @return mixed
     */
    public function findProductBySlug($slug)
    {
        $product = Product::where('slug', $slug)->first();

        return $product;
    }
}

product controller:

<?php

namespace App\Http\Controllers\Site;


use Cart;
use DB;
use App\Models\Product;
use App\Models\Category;
use App\Models\Brand;
use App\Models\Order;
use Illuminate\Http\Request;
use App\Contracts\ProductContract;
use App\Http\Controllers\Controller;
use App\Contracts\AttributeContract;
use App\Contracts\OrderContract;



class ProductController extends Controller
{
    protected $productRepository;

    protected $attributeRepository;
    protected $orderRepository;

    public function __construct(ProductContract $productRepository, AttributeContract $attributeRepository, OrderContract $orderRepository)
    {
        $this->productRepository = $productRepository;
        $this->attributeRepository = $attributeRepository;
    }
    public function index(Request $request)
    {   
        $pagination = 2;


        if (request()->sort == 'low_high') {
            $products = Product::where('status', '1')->orderBy('price')->paginate($pagination);
        } elseif (request()->sort == 'high_low') {
            $products = Product::where('status', '1')->orderBy('price', 'desc')->paginate($pagination);
        } else {



       $products = Product::where('status', '1')->OrderBy('name', 'asc')->paginate($pagination);
    }
        return view('site.pages.products', compact('products' ));

}
public function search( Request $request) {
    $request->validate([
        'q' => 'required'
    ]);
    $q = $request->q;

    $filteredProducts = Product::where('name', 'like', '%' . $q . '%')->where('status', '1')->paginate(2);
    if ($filteredProducts->count()) {
        return view('site.pages.products')->with(
            'products' ,  $filteredProducts
        );
    } else {

        return redirect('/products')->with(
            'status' , 'search failed ,, please try again'
  );
    }

}
    public function show($slug, $id='')
    {
        $product = $this->productRepository->findProductBySlug($slug);


        $attributes = $this->attributeRepository->listAttributes();
        $productCategories=DB::table('product_categories')->get();


        $products = Product::where('id', '!=' ,$product->id)->where('status','1')->orderby('id','desc')->get();
        return view('site.pages.product', compact('product', 'attributes', 'productCategories', 'products'));
    }


    public function addToCart(Request $request)
    {
        $product = $this->productRepository->findProductById($request->input('productId'));
        $options = $request->except('_token', 'productId', 'price', 'qty');

        if($product->quantity<1){

            return redirect()->back()->with('error', 'Cant add Item to cart.');
        }

        Cart::add(uniqid(), $product->name, $request->input('price'), $request->input('qty'), $options);


        return redirect()->back()->with('message', 'Item added to cart successfully.');

    }


}

product.blade.php:

product Model:

category Model:

product_categories table:

How to&Answers: