Trying to delete multiple records at once in Laravel - php

I'm trying to make table with checkboxes where admin can check multiple products and delete them. So far I've made the form
#foreach($products as $product)
{{ Form::open() }}
<input type="checkbox" name="delete[]" value="{{ $product->product_id }}">
<a class="btn btn-primary" href="{{ URL::to('/admin/products/multiDdelete') }}?_token={{ csrf_token() }}">Delete</a>
{{ Form::close() }}
#endforeach
This is in my route
Route::get ('/admin/products/multiDdelete', ['uses' => 'AdminController#testDelete', 'before' => 'csrf|admin']);
And this in the controller
public function testDelete() {
$delete = Input::only('delete')['delete'];
$pDel = Product::where('product_id', $delete);
$pDel->delete();
return Redirect::to('/admin/test')->with('message', 'Product(s) deleted.');
}
So far when I check products and hit Delete page reload and I get Product(s) deleted but products aren't deleted. I think the problem is in how I pass ID's.. but I can't figured it out.

Your query isn't returning anything useful here. Even with ->get(), it would return a collection, which you can't use the way you want. You can add delete to your query instead:
Product::whereIn('product_id', $delete)->delete();

Related

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

i want to do seller can delete the product
<form action="{{ route('product.destroy'}}" method="post">
{{csrf_field()}}
{{method_field('DELETE')}}
<button type="submit" class="btn btn-sm btn-danger">Delete</button>
</form>
this is in web.php
Route::get('/index', 'ProductController#index');//seller view all product
Route::get('/create', 'ProductController#create'); //seller create new product
Route::post('','ProductController#store')->name('product.store'); //store in database
Route::get('/edit/{id}','ProductController#edit'); // seller edit post
Route::put('edit/{id}','ProductController#update')->name('product.update'); //seller update
Route::delete('/{id}','ProductController#destroy')->name('product.destroy');//seller delete product
this is in ProductController
public function destroy($id)
{
$product= Product::find($id);
Storage::delete($product->image);
$product->delete();
return back()->withInfo('Product has been deleted');
}
HELP me please
I think you are missing ID do it like
{{ route('product.destroy', $product->id)}}
you can try removing the post method of the form cause you specify another one and depend on which version you are using you can try #method('DELETE')
#method('DELETE')
it just more elegant
Pass the ID in the route in form tags,
{{ route('product.destroy', $product->id)}}
Also
$product= Product::find($id);
Storage::delete($product->image);
$product->delete();
Check if their is a $product, then delete it, otherwise you'll get an error.

Laravel Delete Method: MethodNotAllowedHttpException in RouteCollection.php line 233:

I tried to delete the cart from a list. When I tried to delete it, it shows an Error. Below here is my code:
Web.php
Route::post('cart/delete/{id}','ProductController#deleteCart');
blade.php
<a href="{{ url('/cart/delete',$row->id) }}" class="remove_item">
<i class="fa fa-times"></i>
</a>
<form action="{{ url('/cart/delete',$row->id)}}" method="POST" style="display: none;">
{!! Form::hidden('id',$row->id) !!}
</form>
Controller.php
public function deleteCart($id){
$cart = Cart::find($id);
$cart->destroy();
return Redirect::to('/shop-cart');
}
Simply change the following line of code:
Route::post('cart/delete/{id}','ProductController#deleteCart');
into:
Route::get('cart/delete/{id}','ProductController#deleteCart');
Reason for this error is sending a GET request to a POST route. In your code you are sending a GET request by calling a URL.
<a href="{{ url('/cart/delete',$row->id) }}" class="remove_item">
<i class="fa fa-times"></i>
</a>
Or otherwise if you want to keep the route as it is (as a POST route) just use the following code and make some adjustments accordingly:
<form action="{{ url('/cart/delete') }}" method="POST" style="display: none;">
{!! Form::hidden('id', $row->id) !!}
<input type="submit" value="Submit">
</form>
And it is better to modify the route as follows as the '/{id}' part is not needed as we are sending the id along with the POST request:
Route::post('cart/delete','ProductController#deleteCart');
Import Http\Request into your controller using:
use Illuminate\Http\Request;
And update your controller function as follows:
public function deleteCart(Request $request){
$cart = Cart::find($request['id']);
$cart->destroy();
return Redirect::to('/shop-cart');
}
But for this scenario GET route seems a good choice to avoid complexity.
Remove a href link, because it will send GET request, instead of POST. Add submit button to the form:
<form action="{{ url('/cart/delete/'.$row->id) }}" method="POST" style="display: none;">
{!! Form::hidden('id', $row->id) !!}
{!! Form::submit('delete') !!}
</form>
The error say that there is no route like the one you try to call. you have a route like this in your route file : /cart/delete/{id} where expects an id, and you call this from your form /cart/delete?id=theid
Fix
Change this from your submit url : /cart/delete',$row->id)
To this: /cart/delete/{{$row->id}}

delete function Laravel 5.2

I've been learning laravel 5.2 recently, and i've made a delete function which should delete records from my database but instead of deleteing the records it's adding a blank row into my database
This is the Route im using:
Route::resource('producten', 'ProductenController', ['only' => ['index', 'store', 'destroy', 'edit', 'update', 'create']]);
This is the controller function i use for it
public function destroy(request $request , product $product)
{
$product->delete();
return redirect(Route('producten.index'));
}
This is the form i've made for it.
{{ Form::Open(['Route' => 'producten.destroy', $product], ['method' => 'delete']) }}
{{ Form::Submit('delete')}}
{{ Form::close() }}
when i viewed the source-code it said it was using a POST method instead of a delete method, and also when i add($product) i got a blank page, also i found out that when i hit the submit button it goes to the store method i've made and i dont know why,
if u need more information just let me know and i'll add it in the question
route and method should be in the same array, not in two differents arrays.
{{ Form::Open(['method' => 'DELETE', 'route' => ['producten.destroy', $product]]) }}
{{ method_field('DELETE') }}
{{ Form::Submit('delete')}}
{{ Form::close() }}
I think you have something wrong with form. Can you try with this:
<form action="{{ route('producten.destroy', ['product' => $product->id]) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit">Remove</button>
</form>

How do I give a variable to my blade and save them to a variable?

My problem is a little bit complicated to explain. I'm doing a blog and did something like a topic section. I have a topic table and a thread table. In my thread table is a 'topic' attribute. No I want that if I'm doing a new thread, I also want to save the topic, the user currently is in right now.
My send button with the variable is this:
<a href="{{ action('Test\\TestController#add', [$thread->thema]) }}">
<div class="btn btn-primary">Thread hinzufügen</div>
</a>
My add-route:
Route::get('/add/{thread}', 'Test\\TestController#add');
My controller function just send's me to the thread creating form.
My creating thread - form :
{!! Former::horizontal_open()->action(action('Test\\TestController#store')) !!}
{!! Former::text('thread')->label('Title:')->autofocus() !!}
{!! Former::textarea('content')->label('Content')->rows(10) !!}
{!! Former::large_primary_submit('Add Thread') !!}
{!! Former::close() !!}
Well, after I pressed the submit button, the thread get saved, but without the topic! :/
According to the following route:
Route::get('/add/{thread}', 'Test\\TestController#add');
You'll get the $thread->thema inside your TestController#add method so your method should be able to recieve that param/variable, for example:
public function add($thread)
{
// Now you may pass the $thread to form and keep the value in a hidden
// text box, to pass to the for the form, add the $thread using with:
return view('FormView')->with('thread', $thread);
}
In the form, create a hidden input:
<input type="hidden" name="thread" value="{{ old('thread', $thread) }}" />
Or maybe this (if it works, not sure about the former tho):
{!! Former::hidden('thread', old('thread', $thread))->label('Title:')->autofocus() !!}

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