how can we update existing data using a foreign key in laravel 7?

First of all, your validation was not passing and that’s why you were being redirected. Now the second problem is route model binding. your route model binding is not working. Bind object is new and that is why it’s saving a new entry in db. Your routes are

Route::resource('moneytrade', 'MoneyTradeController')->middleware('auth');
Route::patch('/account-renew/{moneytrade}', '[email protected]')->name('mt.update')->middleware('auth'); 

Look your uri moneytrade is moneytrade but in your controller you are binding object as moneyTrade where T is capital. In route model binding, Laravel expects the uri segment and the bind object same. Otherwise model binding won’t work. If you dd your $moneyTrade object you will find it empty. So the solution here is either change the url or the controller object. If you change route, they will be like

Route::resource('money-trade', 'MoneyTradeController')->middleware('auth');
Route::resource('moneyTrade', 'MoneyTradeController')->middleware('auth');
Route::patch('/account-renew/{moneyTrade}', '[email protected]')->name('mt.update')->middleware('auth');

And you don’t have to change your controller code. If you want to change the controller but not the route then your controller would be

public function update(Request $request, MoneyTrade $moneytrade)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top