1

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?

1 Answers1

0

change this

$event->tickets->pivot->ticket_quantity -= $value;

to this

$vent->tickets()->attach(id, ['ticket_quantity' => $value]);

You can also use sync which deletes the extra entries which are not in your input

$vent->tickets()->sync(id, ['ticket_quantity' => $value]);

Hope this helps

FULL STACK DEV
  • 15,207
  • 5
  • 46
  • 66
  • I need first to get the value from a `pivot` table, then update it by substracting this value to a number which I get from the `request`. Will be trying to use ur solution) – Камилов Тимур Mar 13 '18 at 11:04