2
votes

I'm building a friendship system in Laravel 5 that requires a user to accept a potential friendship with another user.

I've created a many-to-many relationship between users and "helpers" (other users). The relationships look like this:

// Accepted Friendships
function friendsOfMine()
{
  return $this->belongsToMany('App\User', 'helpers', 'user_id', 'helper_id')
    ->wherePivot('accepted', '=', 1);
}

// Potential Friendships
function potentialFriendsOfMine()
{
  return $this->belongsToMany('App\User', 'helpers', 'user_id', 'helper_id')
    ->wherePivot('accepted', '=', 0);
}

The only difference between them is an additional value in my "helpers" pivot table: "accepted." "Accepted" is a boolean that defaults to 0.

I create the table row when a user first proposes friendship, and then would like to update the row when the friendship is accepted. Here is a version of my controller that condenses the two actions into a single code block:

public function store()
{
    $currentUser = Auth::user();
    $input = Input::get('helper_id');
    $helper = User::find($input);

    /* Creates "unaccepted" relationship */
    $currentUser->friendsOfMine()->attach($helper);

    /* Fetches newly created relationship */
    $accepted = $currentUser->potentialFriendsOfMine()->where('helper_id', $input);

    /* Updates "accepted" column and saves */
    $accepted->pivot->accepted = 1;
    $accepted->pivot->save();
    Flash::success('You are now following this user.');
    return Redirect::back();
}

However, I'm getting an error on this line—$accepted->pivot->accepted = 1;—that reads: Creating default object from empty value.

In this case, how would I access and update a value in a pivot table record that I just created?

1
sorry i got confused, what is pivot again? a table?Rash
Hi @Rash, in this case, I have a pivot table called "helpers" with the values "user_id," "helper_id," and "accepted." I'm struggling to figure out how to access and updated that "accepted" value.Cameron Scott
hmm..I know that laravel does not bring "foreign" tables until you say them to..have you read about the "with()" function. If I have User and Helper table attached, I instruct laravel to bring the helper table by using User::with('helper')->where()->get()Rash

1 Answers

3
votes

This line: $accepted = $currentUser->potentialFriendsOfMine()->where('helper_id', $input); returns a Builder object. I think you have forgotten to add ->get() at the end to get a model object. In other words:

$accepted = $currentUser->potentialFriendsOfMine()->where('helper_id', $input)->get();

OR

$accepted = $currentUser->potentialFriendsOfMine()->where('helper_id', $input)->first();