W
W
WebDev2018-05-04 15:33:29
Laravel
WebDev, 2018-05-04 15:33:29

How to add method data to the selection in laravel?

Hello, there is a Product model. Added prevProduct() and nextProduct() methods to the model:

public function prevProduct()
    {
        $id = $this->attributes['id'];

        $prev_product = Product::where('id', '<', $id)->first();

        if ($prev_product) {
             $prev_product = Product::where('id', '>', $id)->first();
        }

        return $prev_product;
    }

How can I add the results of this method to the selection?
That is something like this:
$product = Product::with('prev_product')->where('id', 2)->first();
dd($product->prev_product);

In this case, Call to undefined method Illuminate\Database\Query\Builder::prev_product() swears.
I tried adding these fields to $appends and renaming them to getPrevProductAttribute, but in this case, a loop is obtained.
How to be?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Talalaev, 2018-05-04
@neuotq

Answer based on updated data
Somewhere in the Product model (updated added validation)

protected $appends = ['prev_product_json'];

 public function getPrevProductJsonAttribute()
  {	    
      $product = Product::where('id', '<', $this->id)->first() ?? Product::where('id', '>', $this->id)->first();
      return isset($product) ?  $product->toJson() : NULL;
  }

Well, after that, where necessary:
$product = Product::find(2);
dd($product->prev_product_json);

PS just think right away, maybe you need to go through the fields and create a list of fields that should not be displayed in json , then in the model we doprotected $hidden = ['field_name'];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question