Files
getgreen-backend/app/Http/Controllers/API/ProductController.php

65 lines
1.9 KiB
PHP
Executable File

<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\Http\Resources\ProductDetailResource;
use App\Http\Resources\ProductPaginationResource;
use App\Models\Currency;
use App\Models\Product;
class ProductController extends Controller
{
public function show($product_id)
{
$product = Product::where('published', true)->find($product_id);
if (!$product) {
return response()->json(['message' => 'Product not found'], 404);
}
$currency = Currency::latest()->first();
// add currency to cache
cache()->put('currency', $currency, now()->addMinutes(60));
// increment views
$product->increment('views');
return ['data' => new ProductDetailResource($product)];
}
public function search()
{
if (request()->has('query') && request('query') !== '' && request('query') !== null) {
$products = Product::query()->where('published', true);
$products->where('name->uz', 'ILIKE', '%' . request('query') . '%')
->orWhere('name->ru', 'ILIKE', '%' . request('query') . '%');
return (new ProductPaginationResource($products->paginate($request->limit ?? 10)))->response();
}
return response()->json([
"pagination" => [
"current" => 1,
"previous" => null,
"next" => null,
"total" => 0,
"perPage" => 10,
"totalItems" => 0
],
'data' => []
], 200);
}
public function productsByBrand($brand_id)
{
$currency = Currency::latest()->first();
// add currency to cache
cache()->put('currency', $currency, now()->addMinutes(60));
$products = Product::where('brand_id', $brand_id)->where('published', true)->paginate(10);
return (new ProductPaginationResource($products))->response();
}
}