Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ponnydalen's avatar

Get price of product in array

Hello. I have 3 checkboxes

                 <div class="mx-auto">
                    @foreach($services as $service)
                        <div class="row">
                            <div class="form-check">
                                <label>{{$service->name}}</label>
                                <input class="service_type" type="checkbox" name="service_type[]" value="{{ $service->service_type }}" @if (in_array($service->service_type, $booking->service_type)) checked="checked" @endif>                                                    
                            </div>
                        </div>
                    @endforeach
                </div>

I am using them with ajax so I can return the price from db when I click on them. In ajax I get the values like this:

var service_type = $("input[name^='service_type']:checked").map(function (idx, ele) {
                    return $(ele).val();
                    }).get();

                    alert(service_type);

And I get the values (1,2,3) matching the ID if I click on them, and so far so good.

In Controller

   $booking = Booking::find($id); // Get user ID
$service_type = $request->service_type; // Get values from "form"
$service_type = Service::where('service_type', $service_type)->get();

return response()->json([
    'service-price' => $service_type->price, // Here I want to return the price column for the matching service
]);

"Property [price] does not exist on this collection instance."

So If $service_type contains ["1","2","3"] if everything is checked, and I try to match it with the service type column in service table, why dosent that work?

0 likes
11 replies
deepu07's avatar

@ponnydalen you can use pluck function like this

use Illuminate\Support\Arr;

$array = [
    ['developer' => ['id' => 1, 'name' => 'Taylor']],
    ['developer' => ['id' => 2, 'name' => 'Abigail']],
];

$names = Arr::pluck($array, 'developer.name');
ponnydalen's avatar

Hello and thanks for answer. I get it to work by doing:

$services = Service::whereIn('id', $service_type)->pluck('price');
    $services_total = collect($services)->sum();

Now I got a new problem. In my return response I trying to send the total value of everyting together. Looks like this:

 $price = Price::where('days', '=', $days)->first();
    $products = Product::where('car_care', '=', $car_care)->first();

    $services = Service::whereIn('id', $service_type)->pluck('price');
    $services_total = collect($services)->sum();
    
    if($price) {

        $booking->parking_price = $price->price * ($car_size/100);
        $booking->update();

        return response()->json([
        
            'days' => $days,
            'price' => $price->price * ($car_size/100),
            'productprice' => $products->price,
            'productname' => $products->name,
            'pricetotal' => $services_total + $products->price + ($price->price * ($car_size/100)),
         
        ]);
    }
    else {
        $daysExtended = (($days - 21) * 20) + 750;
        $booking->parking_price = $daysExtended * ($car_size/100);
        $booking->update();

        return response()->json([
         
            'days' => $days,
            'price' => $daysExtended * ($car_size/100),
            'productprice' => $products->price,
            'productname' => $products->name,
            'pricetotal' => $services_total + $products->price + ($daysExtended * ($car_size/100)),
           
        ]);
    };

So, if I product or the service is NOT empty everything works just perfect like it should. But if I uncheck the checkboxes so it return nothing I get error.

"Property [price] does not exist on this collection instance."

I can put some if statements like this

if($product) {
$products = Product::where('car_care', '=', $car_care)->first();
}

And then if statement for another model and so on...But if the if statement actually is true? That means it will not go trough the other if statements? How can I do this?

MichalOravec's avatar

This is the same what you had before, but shorter. In Product instead of first() use firstOrFail()

$product = Product::where('car_care', $car_care)->firstOrFail();

$price = Price::where('days', $days)->first();

$servicesTotal = Service::whereIn('id', $service_type)->sum('price') ?? 0;

$daysExtended = (($days - 21) * 20) + 750;

$booking->update([
    'parking_price' => $parking_price = ($price ? $price->price : $daysExtended) * ($car_size / 100)
]);

return response()->json([
    'days' => $days,
    'price' => $parking_price,
    'productprice' => $product->price,
    'productname' => $product->name,
    'pricetotal' => $servicesTotal + $product->price + $parking_price
]);
ponnydalen's avatar

Thank you Michal, looks like it's working good, but the $product gives me this:

"message": "No query results for model [App\Product].",

Booking Model:

  public function product()
{
    return $this->belongsTo('App\Product', 'car_care');
}

Product model:

 public function booking() {
    return $this->hasOne('App\Booking');
}

Any ideas?

MichalOravec's avatar

It means you don't have any product for that $car_care.

Why do you use car_care as foreign key? So weird.

Booking

public function product()
{
    return $this->belongsTo('App\Product', 'car_care');
}

Product

public function booking() {
    return $this->hasOne('App\Booking', 'car_care');
}
ponnydalen's avatar

Because in my Booking table I have a column called car_care, and in my product table I also have a car_care column. So they could match? Or that very wrong way?

MichalOravec's avatar

If you have relationship One To One them your bookings table has to have product_id

products
    id - integer
    // other fields

bookings
    id - integer
    product_id - integer
    // other fields

Product model

public function booking() {
    return $this->hasOne('App\Booking');
}

Booking model

public function booking() {
    return $this->belongsTo('App\Product');
}

Of course you can have different name for foreign key.

ponnydalen's avatar

When trying to get the servicesTotal I get this if nothing is checked:

"Argument 1 passed to Illuminate\Database\Query\Builder::cleanBindings() must be of the type array, null given

So...I try put my $servicesTotal variable like this:

$serviceTotal = Service::whereIn('id', [$service_id])->sum('price') ?? 0;

Then it works if nothing is checked and it gived me the value of the price of the checked item. Like this callled serviceprice

{"days":24,"price":810,"productprice":0,"productname":0,"pricetotal":1060,"serviceprice":"250","pVAT":106.10420949146484,"tVAT":29.96978282241487}

Which is fair enough, but If I check one more checkbox, i get no errors...but the checkboxes will not sum..I only get the value of one of the checkboxes.

So if I then do this with out [] , like this :

 $serviceTotal = Service::whereIn('id', $service_id)->sum('price') ?? 0;

Then I get the sum of everything but if nothing checked its getting error. So what can I do do make it work ? :)

MichalOravec's avatar
Level 75

@ponnydalen Change it to this.

$serviceTotal = Service::whereIn('id', $service_id ?: [])->sum('price') ?? 0;

And mark this thread as solved. Thanks.

Please or to participate in this conversation.