Why might the Elequent ORM relationship feel empty?

Here is my method available in the controller

    public function getProductListAll(){
        $products = Product::with('property')
            ->where('show', 1)
            ->where('code', '!=', 1)
            ->with(['prices_roket' => function ($q) {
                return $q->whereNull('user_id');
        $products = $products->whereIn('product_type', ['education', 'consultancy', 'startup']);

        $data['products']   = $products->select([
                'id', 'name', 'image', 'commission', 'price',
                'buy_now', 'type', 'short_desc', 'pricing_desc',
                'offer_status', 'period_status', 'period', 'period_frequency',
                'endpoint', 'product_type', 'unique_id', 'discount_show_status',
                'annual_payment', 'pre_register', 'privacy_status', 'privacy',
                'sg_project', 'last_pre_register_date', 'product_desc',
                'product_consulting', 'product_status',

        return response()->json($data);


and here is the relationship in my model.

 return $this->hasMany(ProductPrice::class)->select('price','created_at','user_id','offer_id')
            ->where(function ($q) {
                    ->where(function ($q2) {
                    ->orWhere(function ($q2) {
                        $q2->where('user_id', auth()->user() ? auth()->user()->id : 0);

I tried to change my relationship and rewrite it, but when I write select, I cannot access any data. When I remove select, they all come. I can’t select at prices relationship.

>Solution :

You can not use ->select() inside your model relationship.

Instead what you can do to limit the selection is by adding it into ->with()

For example

$products = Product::query()
   ->with(['property' => function ($q) {
   ->where( ... )
   // no need to add property 'price' inside this select
   ->select(['id', 'name', 'image', 'commission' ... ])

Leave a Reply