Hi Developers,
While developing any web application like admin panel sometimes the user will accidentally delete any table record which will be very important for their business. Without using soft delete the record will be completely deleted from the database which we cant retrieve later, therefore laravel offers soft delete option to provide solution for that.
Lets learn How to use Soft Delete in Laravel 10 in step by step while using the soft delete the record wont be deleted completed from the database instead it will mark the timestamp in deleted_at column in a table when the delete command was executed. However while fetching data from the database using the model by default laravel fetches only the data where the deleted_at was not NULL. However the deleted record are fetched by using the withTrashed() , Lets see by using the step by step example.
Create the migration table with the column softDeletes()
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSamplesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('samples', function(Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop("samples");
}
}
In the model file we should import
use Illuminate\Database\Eloquent\SoftDeletes;
and also use SoftDeletes
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Sample extends Model
{
use SoftDeletes;
public $fillable = ['title','description'];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
}
Lets delete the record while deleting the record won't be deleted from the database instead it marks the date like timestamp in the deleted_at column
$data = Item::find(1)->delete();
While fetching the data from a table through model by default it fetches the data where deleted_at is NULL
$data = Item::get();
To get all the deleted records we should use withTrashed() which will get all the data where deleted_at is not NULL
$data = Item::withTrashed()->get();
We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.
Be the first to know about releases and tutorial news and solutions.
We care about your data in our privacy policy.
ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.
Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides