Search code examples
laravelapirest

Create function endpoint: endpoint: /api/product/get_data/{id}


i have two tables, 'products' and 'sellers'

`Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->foreignId('seller_id');
        $table->string('product_name');
        $table->string('product_size');
        $table->integer('quantity');
        $table->timestamps();

        $table->foreign('seller_id')->references('id')->on('sellers');`

`Schema::create('sellers', function (Blueprint $table) {
        $table->id();
        $table->string('seller_name');
        $table->timestamps();
    });`

How to create function for show only product_name, product_size and seller_name aslo how to create validation for product_size need bigger then 2(for example)

i create ProductResource

        `phone_name' => $this->product_name,
        'display_size' => $this->product_size,
        'seller_name' => SellerResource::collection($this->whenLoaded('seller'))`

but return only product_name and product_size.

And create relationships one to many

I try to: create validate on method 'show'

       response()->validate([
        'product_size' => ['numeric|min:5']
        ]);

try to filter bu operator 'like'. try to create 'Requests'

    public function rules(){
    return [
        'product_size' => 'numeric|min:5'
    ];
}

data needs only show and validate


Solution

  • It almost sounds like you need to create a custom validator. Does that make sense?

    The custom validator might look like

    class ProductSizeValidationRequest extends FormRequest
    {
        /**
         * Determine if the user is authorized to make this request.
         *
         * @return bool
         */
        public function authorize()
        {
            return true;
        }
    
        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {
            return [
                'product_size' => 'numeric|min:2',
            ];
        }
    }
    

    You'd use it like this. UNTESTED, I hope this makes sense https://laravel.com/docs/9.x/validation#custom-validation-rules

    public function show($id)
    {
        $product = Product::findOrFail($id);
    
        $this->validate(request(), (new ProductSizeValidationRequest)->rules());
    
        return new ProductResource($product);