laravel 5 not deleting user record - laravel

All i want to do is simply delete a user form the database.
My Route is a resource as seen below:
Route::resource('users', 'UserController');
So this should mean that the destroy action in my UserController should be the place for my code.
So my controller action is below:
public function destroy($id)
{
$user = User::find($id);
$user->delete();
return Redirect::back();
}
Now when i click the delete button, which links to /users/destroy/4
it should find the user with id 4 and then delete it.
Instead i get the error
NotFoundHttpException in RouteCollection.php line 145:
EDIT:
#foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->username }}</td>
<td>{{$user->HWID}}</td>
<td>{{$user->name}}</td>
<td class="tools">
<i class="fa fa-pencil-square-o fa-lg"></i>
<i class="fa fa-trash fa-lg"></i>
</td>
</tr>
#endforeach

I dont know if it's possible to directly delete a user from your database via a link as you specified in your table.
My work around for this is to first point the user to the show function in your controller. And giving the user an overview of the information of the user itself.
This page contains a form with the DELETE method. Below the information of the user I put a delete button which will submit the form with the DELETE method to the URL: /users/4
Cause the link: /users/destroy/4 is not a valid resource link.
See this link for extra information about the resource controller links: Resource Controller
Example delete/show page of my own application:
{!! Form::model($ManagementUser, array('method' => 'DELETE', 'url' => 'admin/management/' . $ManagementUser->id, 'role' => 'form')) !!}
<div class="box-body">
<div class="form-group">
<label>Name</label>
{!! Form::text('name', Input::old('name'), array('class' => 'form-control', 'placeholder' => 'Name', 'name' => 'name', 'disabled')) !!}
</div>
<div class="form-group">
<label>E-mailaddress</label>
{!! Form::text('email', Input::old('email'), array('class' => 'form-control', 'placeholder' => 'E-Mail', 'name' => 'email', 'disabled')) !!}
</div>
{!! Form::submit('Delete', array('class' => 'btn btn-block btn-default')) !!}
</div>
{!! Form::close() !!}

In Resource Controller, destroy action is handled by DELETE method. Not GET method. Currently you are accessing a route with GET method that is not registered. The following command will help you to understand Resource Routes that you registered.
php artisan route:list
GET
<i class="fa fa-trash fa-lg"></i>
DELETE (You can delete the record by using form and DELETE method as follows)
<form action="{{ route('users.destroy', $user->id) }}" method="POST">
<input type="hidden" name="_method" value="DELETE" />
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>" />
<button><i class="fa fa-trash fa-lg"></i></button>
</form>
Reference
Resource Controller
Method Spoofing

Related

The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST

I am creating an index form that displays some data. Everything is ready but when I make the delete button I get an error "The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST."
Route
Route::group(['middleware' => ['auth']], function() {
Route::resource('roles','RoleController');
Route::resource('users','UserController');
Route::resource('kamar_theresia','Kamar_TheresiaController');
});
Controller
public function destroy($id)
{
Kamar_Theresia::find($id)->delete();
return redirect()->route('kamar_theresia.index')
->with('success','Kamar Theresia deleted successfully');
}
View
#foreach ($kamar_theresia as $tere)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $tere->nama }}</td>
<td>{{ $tere->name }}</td>
<td>{{ $tere->ketersediaan }}</td>
<td>
#can('theresia-delete')
{!! Form::open(['method' => 'DELETE','route' => ['kamar_theresia.destroy', $tere->id],'style'=>'display:inline']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
#endcan
</td>
</tr>
#endforeach
That's because the you're passing DELETE method as the method of your form, and it is wrong, the right thing to do is pass de POST method.
Check this example:
<form action="{{ route('kamar_theresia.destroy', $tere->id) }}" method="POST">
#csrf
#method('delete')
<button type="submit" class="btn btn-outline-danger">Delete</button>
</form>
Your controller should be:
public function destroy(Kamar_Theresia $khamar_teresia)
{
$khamar_teresia->delete();
return redirect()->route('kamar_theresia.index')
->with('success','Kamar Theresia deleted successfully');
}
Make sure you do not have your form inside another form. I made this silly mistake and got the same error message.
Looks like you're almost there! I would use POST for the form similar to this:
{{ Form::open(['method' => 'POST', 'route' => ['kamar_theresia.destroy']) }}
{{ Form::hidden('id',$tere->id) }}
{{ Form::submit('Delete') }}
{{ Form::close() }}
and then in your controller
public function destroy(Request $request){
$id = $request->input('id');
Kamar_Theresia::find($id)->delete();
The rest of your code should be ok. Let me know if this doesn't work.
Use the {{ csrf_field() }} and {{ method_field('DELETE') }} into Form.
{{ csrf_field() }}
{{ method_field('DELETE') }}
Use this into Controller
public function destroy($id)
{
$delete = kamar_theresia::find($id);
$delete->delete();
return redirect('/')->with('deleted','Kamar Theresia deleted successfully');
}
if we are using Route::resource() then it will be automatically route with destroy function.
Forgot to put slash in action at start:
<form method="POST" action={{--here=> --}}"/save_edit_delete_order/{{$order_id}}">
#csrf
#method('delete')
......
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Yes, I am</button>
</div>
</div>
</form>
And in resource Controller:
public function destroy($id)
{
return 'kuku';
}
view
<form action="{{route('command.delete',[$command->id,$command->car_id])}}" method="post">
#csrf
{{method_field('delete')}}
<button type="submit" class="btn btn-danger"><i class="fa fa-trash"></i></button>
</form>
web
Route::delete('/commands/{commandId}/{carId}/delete','CommandController#deleteUserCommands')->name('command.delete');

Select box in form blade Laravel

how can I create a select box which is filled with values from the db?
The view is published with the $groups variable. In my select box i need $groups->id (hidden, only for storing) and $groups->name. This is currently my form.
{!! Form::open(array('route'=>'store.invitation')) !!}
<div class="form-group">
{{Form::label('username', 'Username')}}
{{Form::text('username', '', ['class' => 'form-control', 'placeholder' => 'Enter Username'])}}
{{Form::label('groupname', 'Gruppe')}}
{{Form::select($groups->name) }}
{{ csrf_field() }}
</div>
<div>
{{Form::submit('Submit',['class' => 'btn btn-primary'])}}
<a class="btn btn-default btn-close" href="{{ route('home') }}">Cancel</a>
</div>
{!! Form::close() !!}
Thanks
You should pass an array of the data that you get from the db. Like this:
Form::select('size', array('L' => 'Large', 'S' => 'Small'));
This documentation might be old, but thats how you can create Form::select in blade.

Laravel back()->withInput(); not working

I am currently following a video tutorial on a login form. Here's the code used in case Auth::attempt() fails:
return back()->withInput();
This should return the user to the form and fill out the inputs again (email, password). However the fields stay empty, while login is working correctly.
How can I fix this?
This is my form:
{!! Form::open(array('route' => 'handleLogin')) !!}
<div class="form-group has-feedback">
{!! Form::text('email', null, array('class' => 'form-control', 'placeholder' => 'EMail')) !!}
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
{!! Form::password('password', array('class' => 'form-control', 'placeholder' => 'Password')) !!}
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
<label>
<input type="checkbox"> Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
{!! Form::token() !!}
{!! Form::submit(null, array('class' => 'btn btn-primary btn-block btn-flat')) !!}
</div>
<!-- /.col -->
</div>
{!! Form::close() !!}
Edit: Found out that the following code I have works for login but the else statement is not executed when the login credentials are wrong. why?
public function handleLogin(Request $request)
{
$this->validate($request, User::$login_validation_rules);
$data = $request->only('email', 'password');
if(\Auth::attempt($data)){
return redirect()->intended('home');
}else {
return back()->withInput();
}
}
So, as we discussed, the problem is the web middleware. In previous revisions of the Laravel 5.2 framework, if you wanted to enable sessions and error variables, you had to wrap the routes in the web middleware.
As of version 5.2.27, this is not the case anymore, since that middleware group is already applied to all routes, by default.
Knowingly, having version 5.2.27 or later, and using the web middleware group, causes issues with those same variables, common issues are session variables not being passed around, and the $errors variable provided by the class \Illuminate\View\Middleware\ShareErrorsFromSession, that is returned by the Laravel validation API is set, but empty**.
Summary
If you have Laravel 5.2.27 and later, you don't need to wrap the routes in the web middleware group.
If the version is lower than that, then you are required to do so, in order to use session variables and get validation errors.
Sources
https://github.com/laravel/framework/issues/13313
https://laravel.com/docs/5.2/middleware#middleware-groups
Out of the box, Laravel comes with web and api middleware groups that contains common middleware you may want to apply to web UI and your API routes:
App/Http/Kernal.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
'auth:api',
],
];
Take a look at web which contains StartSession and ShareErrorsFromSession which are responsible for session handling so if you want to show validation errors or persist old data then you have to include them in your middleware group. in this case its web.
You Have To make the condiotion if The form has been back with errors, it should been fill out.
The {{old('nom')}} function look for The Previous Filled Value for a given field and echo it.
you can use it as below:
<div class="col-sm-8">
<input type="text"
class="form-control form-control-sm #error('nom') is-invalid #enderror"
id="nom"
name="nom"
placeholder="Ecriver le nom votre ecole "
value="{{old('nom')}}"
>
</div>
try changing
return back()->withInput();
with
return redirect()->back()->withInput(\Input::all()

Laravel href with POST

I'm trying to pass some data to my controller with an action href. I don't know why, but laravel passes the data with GET method, but instead of GET I need a POST. I don't really understand why laravel does that and coulnd't find an answer. I did that multiple times and my syntax seems to be correct. Can somebody have a look over it?
Blade:
<td>
#foreach($products as $product)
<a href="{{ action('ProductsController#delete', $product->id ) }}">
<span class="glyphicon glyphicon-trash"></span></a>
{{ $product->name }},
#endforeach
</td>
My Route:
Route::post('delete', ['as' => 'delete', 'uses' => 'ProductController#delete']);
In my Controller is just a:
public function delete()
{
return 'hello'; // just testing if it works
}
Error:
MethodNotAllowedHttpException in RouteCollection.php line 219....
I know it's a get method, cause if I'm trying to pass the data to my controller, my URL looks like this:
blabla.../products/delete?10
Is anything wrong with my syntax? I can't really see why it uses the get method.
I also tried a: data-method="post" insite of my <a> tag but this haven't worked either.
Thanks for taking time.
When you make a link with an anchor like <a href=example.com> your method will always be GET. This is like opening a URL in your browser, you make a GET request.
You should use a form to make that POST request to the delete method of the controller. Assuming you have the Illuminate HTML package for HTML and forms, you could do this:
{!! Form::open(['method' => 'DELETE', 'route' => $route]) !!}
{!! Form::submit('delete', ['onclick' => 'return confirm("Are you sure?");']) !!}
{!! Form::close() !!}
EDIT:
With a button tag:
{!! Form::open(['method' => 'DELETE', 'route' => $route]) !!}
<button type="submit"><i class="glyphicon glyphicon-remove"></i>Delete</button>
{!! Form::close() !!}
Here's your problem:
<a href="{{ action('ProductsController#delete', $product->id ) }}">
Anchor tags are always submitted over GET. It's a HTTP built in and is not Laravel specific.
POST is used when a form is submitted that specifies the POST HTTP Verb or the HTTP method is invoked by an AJAX request that specifies POST as the HTTP Verb.
Instead consider a submit type button in a form that submits what you need.
<td>
#foreach($products as $product)
<form method="POST" action="{{ route('delete') }}">
<input type="hidden" name="product_id" value="{{ $product->id }}">
{!! csrf_field() !!}
<button type="submit" class="btn">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
{{ $product->name }},
#endforeach
</td>
And then in your controller:
public function delete()
{
// 'Die Dump' all of the input from the form / request
dd( request()->input()->all() );
// 'Die Dump' the specific input from the form
dd( request()->input('product_id') );
}
You will begin to see how GET and POST requests differ in sending of key/value pairs.
For more information:
http://www.tutorialspoint.com/http/http_methods.htm
Best for laravel 7. First define the form with given form id.
#auth
<form id="logout-form" action="{{ route('logout') }}" method="POST"
style="display: none;">
#csrf
</form>
#endauth
Then you can use the anchor tag for logout operation.In background,javascript working.Wherever the logout was fire then action to given form method of post method and logout route was working.
<a class="nav-link dropdown-toggle text-muted waves-effect waves-dark"
href="{{ route('logout') }}" onclick="event.preventDefault();document.getElementById('logout-form').submit();"
id="2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="mdi mdi-logout"></i>
</a>
Most benefit is the form was not loaded unnecesory.If the user was
logged in so far its load otherwise not
Laravel 7
By jQuery:
<form id="form" action="{{route('route_name')}}" method="POST">#csrf</form>
By JS:
<form id="form" action="{{route('route_name')}}" method="POST">#csrf</form>

Adding Route and Perameter in Form action in html in laravel 5

I am unable to get this, My Route is as under;
Route::patch('/info/{iplive}', ['as' => 'info', 'uses' => 'InfoController#index']);
and Here is My Form,
{!! Form::open(['url'=>'info/', 'id'=> 'lookup', 'class' => 'user_form','method'=>'PATCH']) !!}
<div class="row center-block">
<div class="col-lg-6 center-block">
<div class="input-group">
<input type="text" id="lookup" name="lookup" value="" class="form-control" placeholder="Search for Address">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Lookup</button>
</span>
</div>
</div>
</div>
<!--</form> -->
{!! Form::close() !!}
I am in efforts to use a url like, link but unable to get it done :(
your route expects a paramater to be filled in,
try something like this
{!! Form::open(['method' => 'PATCH', , 'id'=> 'lookup', 'class' => 'user_form', 'route' => [ 'info' , $your_iplive_variable]]) !!}
where $your_iplive_variable should be the paramater you wish to fill in.

Resources