I have two models: Event
and Ticket
. I assigned between them Many-To-Many
relationship: Here it is:
Ticket
model:
public function events()
{
return $this->belongsToMany('App\Event');
}
Event
model:
public function tickets()
{
return $this->belongsToMany('App\Ticket');
}
And then I in my Controller I want to update pivot
table data:
public function register(Request $request)
{
$event = Event::findOrFail($request->event);
if(count($event) > 0) {
foreach($request->tickets_type as $key => $value) {
if($value !== null) {
for($i = 0; $i < (int) $value; $i++) {
$sale = new Sale;
$sale->event_id = $request->event;
$sale->event_type = $request->event_type;
$sale->user_id = Auth::user()->id;
$sale->ticket_type = $key;
$sale->save();
$sale->qr = $this->generateQR($sale->event_id, $sale->ticket_type, $sale->id);
$sale->update();
}
$event->tickets->pivot->ticket_quantity -= $value;
}
}
return response()->json([
'success' => true,
'message' => 'Покупка билетов успешно завершена.',
'data' => $request->all()
], 200);
} else {
return response()->json([
'success' => false,
'error' => 'Попытка подмены данных.'
], 403);
}
}
On $event->tickets->pivot->ticket_quantity -= $value;
it throws me an error:
Property [pivot] does not exist on this collection instance.
What's the workaround?