As for laravel to add in the sample data method?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
14 views
Hello, is the Product model. The model added methods prevProduct() and nextProduct():
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 do I add the results of this method in a sample?
That is something like this:
$product = Product::with('prev_product')->where('id', 2)->first(); dd($product->prev_product);


In this case, the curses Call to undefined method Illuminate\\Database\\Query\\Builder::prev_product()
I tried to add these fields in the $appends to rename getPrevProductAttribute, but in this case looping.
How to be?
by | 14 views

1 Answer

0 like 0 dislike
The answer, based on updated data
Somewhere in the Product model (updated added check)
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 then where you have:
$product = Product::find(2); dd($product->prev_product_json);

PS just think, perhaps you need to go through fields and create a list of fields which should not be output in json , then in the model do protected $hidden = ['field_name'];
by

Related questions

0 like 0 dislike
5 answers
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
asked Jun 12, 2019 by s0prano
0 like 0 dislike
4 answers
0 like 0 dislike
2 answers
110,608 questions
257,187 answers
0 comments
40,796 users