#POST form request with model route binding sends an empty user

1 messages · Page 1 of 1 (latest)

tranquil otter
#

When I click the button to add a user as a friend the user is empty when it reaches the store method. When entering xdebug before sending the user is not empty. Do I miss anything?

The form

 <form
    action="{{ route('friends.store', $user) }}"
    method="POST">
    @csrf
    <button type="submit"
            class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
        Add Friend
    </button>
</form>

route

    Route::resource('friends', FriendsController::class)->only(['index', 'show', 'store', 'destroy']);

store function

public function store(User $user): RedirectResponse
    {
        auth()->user()->friends()->attach($user);

        return redirect()->route('friends.index')->with('success', 'Friend added!');
    }
heavy frigate
#

Laravel willc reate the route parameters for your resource using the resource name.. so friends expect $friend in your route.

#

If you want to change it you have to be explicit.

#
Route::resource('friends', FriendsController::class)->parameters([
    'friends' => 'users'
]);
#

You could do that, or you could change it to friends.

route('friends.store', ['friend' => $user])

public function store(User $friend): RedirectResponse
    {
        auth()->user()->friends()->attach($friend);

        return redirect()->route('friends.index')->with('success', 'Friend added!');
    }

#

I think one of those should fix your problem.