Do you have separated models: Product and Price, or is the price a nullable attribute of the Product model?
Jan 22, 2019
9
Level 3
Laravel with Crud Traits
Guys, I need some help. I have a Product and a template for it, the template of these products may just have a price attached to it. When I create a price for the model I need to check if it already has the price, if it has I redirect it to update. How to make?
Level 56
From the database model it is a HasOne relationship.
So to fetch the price directly from the Variation you can add the relationship method on the MotorcycleVariations model as you told the relationship is missing there:
class MotorcycleVariations {
// ...
/**
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function price() {
// If we do not pass the 'id' as the second parameter Laravel will try
// to guess the foreign key in the motorcycle_variations_price
// as motorcycle_variations_id
return $this->hasOne(MotorcycleVariationsPrice::class, 'id');
}
}
So your controller eneds as this:
public function create(Request $request) {
$product = $request->route('variation');
// As it is a hasOne relation, you can fetch it directly
$price = $product->price;
if (is_null( $price )) {
$this->makeCreate();
} else {
$this->makeUpdate();
}
}
1 like
Please or to participate in this conversation.