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

Rocks's avatar
Level 1

Get Minimum value from Second Table in Laravel using relation

I have two tables

  1. Product List

id | name | user_id

  1     Product 1    10  
  2     Product 2    15
  1. Price

id | list_id | price | type

1    1        250      1
2    2        350      2
3    1        500      1
4    2        600      2

Product listing table contain listing details and it is associated with the price table now i want to get all the products list with condition specified and the normal price in addition to that there will be another column named minimum price that will contain minimum price for that product available with every list. For eg. if i have product 1 listing then there i want to add extra field which extract minimum price 250 from price.

Listing::select('*')->whereHas('PriceVal', function($q) use($country) {
                        $q->where('Type','1');
                       })
                      ->selectRaw("count(*) as total")
                      ->where(['user_id' => $userId])->with('PriceVal')
                      ->get();

Relation:

 public function PriceVal()
    {
        return $this->belongsTo('App\Models\Price', 'id', 'list_id');
    }
0 likes
4 replies
andiliang's avatar

hi if i were you , i will make a method inside product list model , using the getter.

    public function getMinPriceAttribute()
    {
        return  $this->PriceVal()->where('type', 1)->exists() ? $this->PriceVal->price  : null ;
	//go to the relationship product list is belong to price so product only has one price
	//here we check if product in price table type = 1 if yes , return its price
    }

fianlly append it

protected $appends = ['min_price'];

https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json

I am not sure if the code works its just my person opinion. I kniw there is more smart to do .thanks

Rocks's avatar
Level 1

@andiliang : Thanks But this is not giving me minimum price of the specific product.

andiliang's avatar

hi @rocks3621 i just test my method is working , what kind of relation between product and price ? from your code your product is belongs to a price.

product model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
    protected $appends = ['min_price'];

    public function price()
    {
    	return $this->belongsTo(Price::class);
    }


    public function getMinPriceAttribute()
    {
    	// return 100; 
        return  $this->price()->where('type', 1)->exists() ? $this->price->price  : null ;
	//go to the relationship product list is belong to price so product only has one price
	//here we check if product in price table type = 1 if yes , return its price
    }
}

price model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Price extends Model
{
    use HasFactory;

}

migration file

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->foreignId('price_id')->constrained()->onDelete('cascade');
            $table->string('name');
            $table->timestamps();
        });
    }

    public function up()
    {
        Schema::create('prices', function (Blueprint $table) {
            $table->id();
            $table->decimal('price', 8, 2);
            $table->bigInteger('type');
            $table->timestamps();
        });
    }

ur relationship is a product belongs to a price , so inside product table there should be a price_id , price is the parent product is the child

how I retrieve it ?

route::get('min-price', function(){

	$product = Product::find(1);
	return $product ;
	// return dd($product->price->type);


});

my record inside my product table is

INSERT INTO `products` (`id`, `price_id`, `name`, `created_at`, `updated_at`) VALUES
(1, 1, 'product1', '2020-10-12 05:37:47', '2020-10-12 05:37:47'),
(2, 2, 'product2', '2020-10-12 05:37:47', '2020-10-12 05:37:47');

price table

INSERT INTO `prices` (`id`, `price`, `type`, `created_at`, `updated_at`) VALUES
(1, '100.00', 1, '2020-10-12 05:37:18', '2020-10-12 05:37:18'),
(2, '200.00', 2, '2020-10-12 05:37:18', '2020-10-12 05:37:18'),


result I get from the route


{
"id": 1,
"price_id": 1,
"name": "product1",
"created_at": "2020-10-12T13:37:47.000000Z",
"updated_at": "2020-10-12T13:37:47.000000Z",
"min_price": "100.00",
"price": {
"id": 1,
"price": "100.00",
"type": 1,
"created_at": "2020-10-12T13:37:18.000000Z",
"updated_at": "2020-10-12T13:37:18.000000Z"
}
}

does this solve your problem ??

AaEzha's avatar

Maybe this will help

$minimumPrice = $product->prices()->orderBy('price', 'asc')->first()->price;

Please or to participate in this conversation.