Apps route redirecting the wrong URL

1.4k Views Asked by At

------Platform Laravel 7x. --------

I am stuck in a simple problem. I can't find the error. While I am updating a form, it redirects to a wrong URL which I don't want and data doesn't update.

Form action url:

 method="POST" action="{{'city/update/'. $editCity->id}}"

form image

Route:

Route::post('city/update/{id}','Admin\CityController@update');

web route

Function from controller:

public function update(Request $request, $id)
    {
        $editCity=City::find($id);
        $editCity->city_name=$request->city_name;
        $editCity->save();
        return redirect()->back();
    }

function from controller

When I click on update it goes to this URL and shows 404 error which I don't want: public/panel/city/edit/city/update/33

Help me to find out the problem where is the mistake I have done. I want to make it updated when I click on the update button and return back.

3

There are 3 best solutions below

4
STA On BEST ANSWER

Use name route instead. So your code will look like :

blade.php

method="POST" action="{{ route('city.update',  $editCity->id) }}"

web.php

Route::post('city/update/{id}','Admin\CityController@update')->name('city.update');
2
Fanhatcha Kone On

In case your CityController is a resource controller, this what you should try:

Route: web.php

Route::resource('city', 'Admin\CityController');   
Form: HTML

<form action="{{route('city.update',$editCity->id)}}" method="post">
Controller: CityController.php

public function update(Request $request, $id)
    {
        $editCity=City::find($id);
        $editCity->city_name=$request->city_name;
        $editCity->save();
        return back()->with('success','city added successfully!');
    }

I hope it helps !

2
Fanhatcha Kone On

While creating your controller did you run such command ?:

php artisan make:controller Admin\CityController --resource

You should create the controller as a resource controller, then declare it

in your routes like this:

Route::resource('city', 'Admin\CityController');  

Ps: Make sure to remove in web.php, your old route:

Route::post('city/update/{id}','Admin\CityController@update')->name('city.update');