Jamie
Jamie

Reputation: 10896

Add values to pivot table laravel

When I want to save a reaction to a ticket I've three tables (in laravel):

-Tickets
-Reaction
-Reaction_Tickets (pivot table)

When I want to save a reaction I do it like this:

public function addReaction(Request $request, $slug)
    {
        $ticket = Ticket::whereSlug($slug)->firstOrFail();
        $reaction = new reactions(array(
            'user_id' => Auth::user()->id,
            'content' => $request->get('content')
            ));

        return redirect('/ticket/'.$slug)->with('Reactie is toegevoegd.');
    }

But now of course it's not added to the pivot table. And I can't add it because I don't have a model of it. What's the right way of doing this?

EDIT:

-Tickets

public function reactions()
{
    return $this->belongsToMany('App\reactions');
}

-Reactions

public function tickets()
{
    return $this->hasOne('App\tickets');
}

Upvotes: 2

Views: 910

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29278

From the Laravel documentation, you need to save and attach the Reaction to the Ticket:

$reaction = new reactions(array(
    'user_id' => Auth::user()->id,
    'content' => $request->get('content')
));
$reaction->save(); // Now has an ID
$tickets->reactions()->attach($reaction->id);

In your Ticket model, you need to have the relationship defined:

class Ticket extends Model {
    protected $table = "tickets";

    public function reactions(){
        return $this->belongsToMany("App\Reaction"); 
    }
}

And you should have the inverse defined on Reaction:

class Reaction extends Model {
    protected $table = "reactions";

    public function tickets(){
        return $this->belongsToMany("App\Ticket"); 
    }
}

If your models are set-up like so, you shouldn't have any issue attaching the new Reaction to your existing Ticket via your pivot table.

Upvotes: 5

Related Questions