Skip to content
Advertisement

Button Soft Delete Not Functioning laravel 8

i’m using laravel 8 to make a function softdeletes. In my view pages, my button is not working and there is no error just not functioning. i’m not sure if this unfunctioning is from the migration or the controller.

So here is my migration

public function up()
{
 Schema::create('products', function (Blueprint $table) {
 $table->id();
 $table->string('name');
 $table->string('detail');
 $table->timestamps();
 $table->softDeletes();
});
}

My product model

use IlluminateDatabaseEloquentSoftDeletes;

class Product extends Model
{
use SoftDeletes;
protected $fillable = [
'name',
'detail'
];
}

my product controller

public function delete($id)
{
$product = Product::where('id',$id) -> first();
$products = Product::all();

if ($product != null) {
$product->withTrashed()->get();
return redirect()->route('pro.index')->with(['message'=> 'Successfully deleted!!']);

}
return view('products.pro_index', ['products' => $products]);
}

My route

Route::get('/delete-index/{id}', [AppHttpControllersProductController::class, 'delete'])->name('delete');

My view button

<a class="btn btn-info" href="{{ route('delete', $product->id) }}">Delete</a>

Will very appreciate if someone willing to help me

Advertisement

Answer

You are never deleting the product in your controller.

You have to call the delete() method:

public function delete($id)
{
   $product = Product::where('id',$id) -> first();
   $products = Product::all();

   if ($product != null) {
      //$product->withTrashed()->get(); useless here
      $product->delete(); // will soft delete the product
      //$product->forceDelete(); // will hard delete the product
      return redirect()->route('pro.index')->with(['message'=> 'Successfully deleted!!']);
   }
   return view('products.pro_index', ['products' => $products]);
}

Please note that you are deleting your product after getting all the products ($products = Product::all(); is before $product->delete();), so you’ll probably need to refresh your page again to actually see the product deleted.

Aside your question, you also should:

  • delete your product inside a DELETE request, not GET
  • redirect to the index route with return redirect()->route('tour_route_name'); (it’ll also solve the problem mentioned above about deleting the product after Product::all())
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement