I am using Laravel framework as a backend API and a few blade PHP files for the front end, specifically for the authentication and the admin panel from the /admin route. In /admin, I display a list of all registered users and buttons next to them. (This page is only visible for users that have their value in Admin column set as true). I want to toggle the Admin status of a user, either promoting or demoting them by clicking the button next to the user name. For this, I tried to use a form submit with get method. I have a method defined inside UserController like this:
public function setAdmin($id) {
$user = User::find($id);
$user->admin = !$user->admin;
if($user->save()) {
echo "Changed";
}
else {
echo "Could not be changed";
}
}
I want to call this method from the view on the click of a button.
I tried using a Form to send a request by specifying the action, but it gave an error saying the values passed are less than the expected number of parameters.
{!! Form::open(['action' => ['UserController@setAdmin', $user->id], 'method' => 'POST']) !!}
{{ Form::submit('Submit', ['class' => 'btn btn-primary']) }}
{!! Form::close() !!}
I have a route set up explicitly to call this action
Route::post('/admin/users/setAdmin', 'UserController@setAdmin')
Although I am not sure if I have to set an explicit route for this action or if it's possible to call a controller function directly from a view without defining the route.
I have iterated through User Model to display all users:
@if(count($users) > 0)
@foreach($users as $user)
<div class="card">
{{ $user }}
</div>
{!! Form::open(['action' => ['UserController@setAdmin', $user->id], 'method' => 'POST']) !!}
{{ Form::submit('Submit', ['class' => 'btn btn-primary']) }}
{!! Form::close() !!}
@endforeach
@else
<h2>No users found!</h2>
@endif
EDIT: Added the foreach section of the blade file. Also I modified the 'action' part of the Form::open() parameters, it was a mistype, the parameters error is still there.
Can someone explain how this can be done?
{!! Form::open(['action' => ['UserController@setAdmin', $user->id], 'action' => 'POST']) !!}here parameter name should be method for postsetAdmindefined in the UserController, or is it a different parameter you are talking about?'action' => 'POST', it should be method not action