I'm trying to setup a simple button to update a db column value when clicked. I can't seem to figure out why my route isn't getting passed my value however?
HTML:
<form method="post" action="{{ route('approveResturant') }}">
{{ csrf_field() }}
<input type="hidden" name="id" value="{{ $resturant->id }}" />
<button type="submit">
Approve
</button>
</form>
Controller:
public function approveResturant($request)
{
dd($request->all());
$id = $request->id;
$resturant = Resturant::find($id);
$resturant->approved = 1;
$resturant->save;
return redirect()->back()->with('message', 'Resturant Approved Successfully!');
}
Route:
Route::post('approveResturant'[ResturantController::class,'approveResturant'])->middleware(['auth'])->name('approveResturant');
And finally, the error itself:
Any help appreciated!
CodePudding user response:
Add the Request
type-hint to your function:
use Illuminate\Http\Request;
public function approveResturant(Request $request)
{
dd($request->all());
$id = $request->id;
$resturant = Resturant::find($id);
$resturant->approved = 1;
$resturant->save;
return redirect()->back()->with('message', 'Resturant Approved Successfully!');
}
The difference here is that Laravel understands the Request
type-hint and knows that it should inject the Request
object from the pre-defined services it has in its service container. Otherwise, Laravel doesn't know where that parameter is coming from so assumes you will provide it. Simply naming your parameter $request
is insufficient.
Update
Do you know why the function would still not be saving the new approved value to the DB?
A few potential reasons:
- You have not removed the
dd($request->all());
statement $resturant = Resturant::find($id);
failed to find a record in the databasesave
is a function not a property so$resturant->save;
should be$resturant->save();
To isolate the exact issue you will need to perform some debugging (e.g. either using xdebug or dd
statements).
CodePudding user response:
Use Request Class
use Illuminate\Http\Request;
public function approveResturant(Request $request)
{
dd($request->all());
$id = $request->id;
$resturant = Resturant::find($id);
$resturant->approved = 1;
$resturant->save;
return redirect()->back()->with('message', 'Resturant Approved Successfully!');
}