PHP code example of tcgunel / ucp-laravel

1. Go to this page and download the library: Download tcgunel/ucp-laravel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tcgunel / ucp-laravel example snippets


namespace App\Ucp;

use App\Models\Product as Listing;
use Tcgunel\Ucp\Contracts\CatalogProvider;
use Tcgunel\Ucp\DTO\Availability;
use Tcgunel\Ucp\DTO\Money;
use Tcgunel\Ucp\DTO\PriceRange;
use Tcgunel\Ucp\DTO\Product;
use Tcgunel\Ucp\DTO\RequestContext;
use Tcgunel\Ucp\DTO\SearchQuery;
use Tcgunel\Ucp\DTO\SearchResult;
use Tcgunel\Ucp\DTO\Variant;

final class EloquentCatalogProvider implements CatalogProvider
{
    public function search(SearchQuery $query): SearchResult
    {
        $listings = Listing::query()
            ->when($query->hasQuery(), fn ($q) => $q->where('name', 'like', "%{$query->query}%"))
            ->limit($query->pagination->limit)
            ->get();

        return new SearchResult(products: $listings->map($this->toUcpProduct(...))->all());
    }

    public function lookup(array $ids, RequestContext $context): array
    {
        return Listing::query()->findMany($ids)->map($this->toUcpProduct(...))->all();
    }

    public function product(string $id, array $selected, array $preferences, RequestContext $context): ?Product
    {
        $listing = Listing::query()->find($id);

        return $listing instanceof Listing ? $this->toUcpProduct($listing) : null;
    }

    private function toUcpProduct(Listing $listing): Product
    {
        $price = new Money((int) $listing->price_in_kurus, 'TRY');

        return new Product(
            id: (string) $listing->id,
            title: $listing->name,
            description: $listing->description ?? '',
            priceRange: PriceRange::uniform($price),
            variants: [
                new Variant(
                    id: (string) $listing->id,
                    title: $listing->name,
                    price: $price,
                    availability: $listing->stock > 0
                        ? Availability::inStock($listing->stock)
                        : Availability::outOfStock(),
                ),
            ],
        );
    }
}

// config/ucp.php
'catalog_provider' => \App\Ucp\EloquentCatalogProvider::class,
bash
php artisan vendor:publish --tag=ucp-config