Why Is Method Spoofing not Working Laravel? - php

I have a form associated with the destroy method to delete a item/record.
<form action="{{ route('climb-excluded.destroy',$exclude->id) }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-danger btn-sm">
<i class="fa fa-trash-o" aria-hidden="true"></i> Delete
</button>
</form>
destroy() method
<?php
public function destroy(Cexcluded $cexcluded)
{
$cexcluded->tours()->detach();
$cexcluded ->delete();
Session::flash('success','Item sucessfully deleted !');
return redirect()->route('climb.ie');
}
Routes
Route::resource('climb-excluded','CexcludedsController', ['only'=>['store','destroy']]);
Route::get('climbing/included-excluded','HomeController#getclimbIE')->name('climb.ie');
The trouble I'm having is the destroy method is not deleting the record from the DB and doesn't give any error. It is giving a session message without deleting the record.

I saw your other thread with the same issue regarding the detach causing problems.
Add this to your Cexcluded model
public static function boot()
{
parent::boot();
static::deleting(function($model) {
$model->tours()->detach();
});
}
Remove the following line from your controller method
$cexcluded->tours()->detach();
So try this
public function destroy(Cexcluded $cexcluded)
{
$cexcluded ->delete();
Session::flash('success','Item sucessfully deleted !');
return redirect()->route('climb.ie');
}

You must use "->destroy()" in the controller.
Check this question for clarification between destroy() and delete()

Related

Route [crops.restore] not defined

I created a resource controller. The problem is when I code a route in my view, the browser displays Route [crops.restore] not defined. I run the php artisan route:list command and I realize that the route does not exist in the route list.
My controller is this
// Display all crops
public function index(Request $request)
{
if ($request->has('trashed')) {
$records = Crop::onlyTrashed()
->get();
} else {
$records = Crop::get();
}
return view('crops.index', compact('records'));
}
//restore a file
public function restore(Request $request, $id)
{
Crop::withTrashed()->find($id)->restore();
return redirect()->back();
}
My route
// Crop controllers
Route::resource('crops', 'CropsController');
My View
#foreach ($records as $crops)
//code ...
#if(request()->has('trashed'))
<a class="btn btn-success btn-sm float-left mr-1" href="/crops/{{ $crops['id'] }}/edit">Edit</a>
Restore
#else
<form method="POST" class="float-left" action="{{ route('crops.destroy', $crops->id) }}">
#csrf
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger delete btn-sm " title='Delete'>Delete</button>
</form>
#endif
#endforeach
What's wrong with my code?
Restore provide this methods in your controller: index, store, edit, update, show, destroy. If you want redirect to your custom method like restore your have to rewrite your route in this matter:
Route::get('/restore', [App\Http\Controllers\CropsController::class, 'restore']);
Just add the route in the web.php file. For example:
Route::get('/restore', '\App\Http\Controllers\HomeController#restore');

How can I delete this Laravel form using get method

The 'Delete' method was not working so I used 'get' but my data is not deleting
<form method="post" class="delete_form" action="{{ url('/data', $row['id']) }}" id="studentForm_{{$row['id']}}">
{{ method_field('GET') }}
{{ csrf_field() }}
<button type="submit" class="btn btn-danger">{{ trans('Delete') }}</button>
</form>
public function destroy($id)
{
dd($id);
$student = Student::where('id',$id)->delete();
return redirect('/data/{id}')->with('success', 'Data Deleted');
}
}
Route::get('/data/{id}','App\Http\Controllers\StudentController#index');
Route::delete('/data/{id}','App\Http\Controllers\StudentController#destroy');
This is I finally got the answer
I ran the following command:
php artisan route:clear
php artisan route:list
Then it gave me suggested methods and delete method was shown for "Controller#destroy" route then I changed from "get" method to "delete" method. Then, my post was able to delete.
The form must be submitted via delete method
<form method="POST" action="{{ url('/data', $row['id']) }}">
#method('DELETE')
#csrf
<button type="submit" class="btn btn-danger">{{ trans('Delete') }}</button>
</form>
More details can be found here: https://laravel.com/docs/8.x/routing#form-method-spoofing

Delete single record Laravel

I'm fairly new to Laravel and would like to create a functionality where I will delete a single record from the database by clicking a link.
Below is the code on the view:
#foreach($companies as $company)
<tr>
<td> {{$company->name}}</td>
<td> {{$company->descriptions}}</td>
<td> {{$company->comptype->name}}</td>
<td>
<i class="fa fa-edit"></i>
<a onclick="
var result = confirm('Are you sure you wish to delete this Company?');
if( result ){
event.preventDefault();
document.getElementById('delete-form').submit();
}
"
class="btn btn-xs btn-default"><i class="fa fa-trash"></i> </a>
<form id="delete-form" action="{{ route('companies.destroy',[$company->id]) }}"
method="POST" style="display: none;">
<input type="hidden" name="_method" value="delete">
{{ csrf_field() }}
</form>
</td>
</tr>
#endforeach
Next is the destroy method in the Controller
public function destroy(Company $company)
{
//
// dd($company);
$findCompany = Company::findOrFail( $company->id);
if($findCompany->delete()){
//redirect
return redirect()->route('companies.index')
->with('success' , 'Company deleted successfully');
}
return back()->withInput()->with('error' , 'Company could not be deleted');
}
The form looks like this:
When clicking on trash, to delete a particular record, the record on the table gets deleted and it doesn't matter which I try to delete, the first record always gets deleted. When I did a diedown, I found that the URL has the correct record but dd shows that the first record will be deleted. I am fairly new to Laravel, I've done this using Laravelcollective/html, but unfortunately it's not compatible with Laravel 5.5.28. Please be so kind to assist
The problem is in JS code. Your JS code always sumbits the same delete form. To fix this, you need to use unique IDs:
<form id="delete-form{{ $company->id }}"
And then:
document.getElementById('delete-form{{ $company->id }}').submit();
Also, mixing JS and PHP is a bad practice. You should really put all the JS into a separate JS file.
Try That way it's my project code :
View File :
<td>
<form action="{{action('TagController#destroy', $row['id'])}}" method="post">
{{csrf_field()}}
<input name="_method" type="hidden" value="DELETE">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
TagController.php:
public function destroy($id)
{
$tags = Tag::find($id);
$success = $tags->delete();
if($success)
{
return redirect('/admin/tag')
->with('success','Tag deleted.');
}
return back()->withInput()->with('errors','Some error...');
}
Try this
see the form action "{{ route('companies.destroy',[$company->id]) }}" to {{ url('companies/destroy/'.$company->id) }}
see the destroy methos in wrong
Click the link
Perfect Method
public function destroy($id){
$findCompany = Company::findOrFail($id);
if($findCompany->delete()){
//redirect
return redirect()->route('companies.index')
->with('success' , 'Company deleted successfully');
}
return back()->withInput()->with('error' , 'Company could not be deleted');}
Try this code for view file :
<div class="col-xs-12">
<a href="{{url('/delete')}}/{{$allDemos[$i]->id}}" class='btndelete'>
<i class="fa fa-trash"></i>
</a>
SliderControler.php :
public function delete($id){
$Slider = Slider::find($id);
unlink('slider_images/'.$Slider->slider_img);
$Slider->delete();
return redirect('/slider');
}
Try this:
public function destroy(Company $company)
{
if($company->delete()){
//redirect
return redirect()->route('companies.index')
->with('success' , 'Company deleted successfully');
}
return back()->withInput()->with('error' , 'Company could not be deleted');
}

Laravel CRUD destroy method not working. Cannot pass data from the view to the controller in order to delete the data

Destroy method not working
I am trying to delete an image from my database but I am receiving the following error:
Undefined variable: portfolio (View: C:\MyProjects\bubblehouseProject\resources\views\admin\portfolio\addPortfolio.blade.php)
I believe there is something wrong with the logic I am trying to implement in my Laravel application. I am using Eloquent ORM.
Controller:
public function Destroy($id) {
$portfolio = new Portfolio();
$portfolio::find($id);
$portfolio->delete();
return redirect('addPortfolio')->with('delete', 'The image has been successfully deleted!');
}
Route:
Route::get('addPortfolio/{id}', 'AddPortfolioController#Destroy');
View:
<form action="{{ route('addPortfolioController.Destroy', $portfolio->id) }}">
<input type="submit" value="Delete" class="btn btn-danger btn-block" onclick="return confirm('Are you sure to delete?')">
<input type="hidden" value="{{ csrf_token() }}" name="_token">
{{ method_field('DELETE') }}
</form>
I am not entirely sure that this is the right way to delete data from the database.
Route
Route::delete('addPortfolio/{id}', 'AddPortfolioController#Destroy')->name('portfolio.destroy');
View
<form action="{{ route('portfolio.destroy', $portfolio->id) }}">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<input type="submit" value="Delete" class="btn btn-danger btn-block" onclick="return confirm('Are you sure to delete?')">
</form>
Controller
public function destroy($id)
{
if(Portfolio::destroy($id)) {
return redirect('addPortfolio')->with('success', 'The image has been successfully deleted!');
} else {
return redirect('addPortfolio')->with('error', 'Please try again!');
}
}

Laravel Eloquent delete by id

I'm trying to delete a single record by id. Instead, it deletes all records in that table.
Here's my code:
View
<form role="form" action="{{ route('status.delete', ['statusId' => $status->id]) }}" method="post">
<button type="submit" class="btn btn-default"><i class="fa fa-times"></i> Delete</button>
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
Routes
Route::post('/status/{statusId}/delete', [
'uses' => '\Dashboard\Http\Controllers\StatusController#deleteStatus',
'as' => 'status.delete',
'middleware' => ['auth'],
]);
Controller
public function deleteStatus(Request $request, $statusId)
{
Auth::user()->statuses()->delete($statusId);
return redirect()->route('home')->with('success', 'Post deleted.');
}
Note: When I dd($statusId) it does provide the right ID for the status I'm deleting. So that part does work.
This is possible in Laravel 5.6 using the destroy method:
From the docs:
However, if you know the primary key of the model, you may delete the
model without retrieving it. To do so, call the destroy method
App\Model::destroy(1);
or to delete an array of ids:
App\Model::destroy([1, 2, 3]);
or by query:
App\Model::where('active', 0)->delete();
Unfortunately, the Eloquent builder does not support passing the id to delete.
Instead, you have to first find to model, then call delete on it:
$request->user()->statuses()->findOrFail($statusId)->delete();
you can delete the model by using another approach like
App\Models\ModelName::find(id)->delete()
but it throws nullPointerException that you have to handle
**Step 1 create route inside web.php**
Route::delete('/answers_delete/{id}', [App\Http\Controllers\AnswerController::class, 'delete'])->name('answers.delete');
**Step 2 Create method in your controller**
use App\Models\Answer; // use in top of this file
public function delete($id)
{
$ans = Answer::find($id);
$ans->delete();
session()->flash('success', 'Answer Deleted Successfully!!!');
return view('admin.anser.index');
}
**Step 3 define your route name inside form action(Note my case view file name index.blade.php and inside admin/answer/index.blade.php)*
<form action="{{ route('answers.delete', $answer->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger" style="display: inline;">Delete</button>
</form>

Categories