Answer the question
In order to leave comments, you need to log in
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;
}
$product = Product::with('prev_product')->where('id', 2)->first();
dd($product->prev_product);
Answer the question
In order to leave comments, you need to log in
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;
}
$product = Product::find(2);
dd($product->prev_product_json);
protected $hidden = ['field_name'];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question