Awalnya diposting @ https://codeanddeploy.com kunjungi dan unduh kode sampel:
https://codeanddeploy.com/blog/laravel/complete-laravel-8-soft-delete-restore-deleted-records-tutorial
Dalam posting ini, saya akan berbagi dengan Anda penghapusan lunak Laravel 8 lengkap dan memulihkan catatan yang dihapus tutorial. Saat mengembangkan operasi CRUD di Laravel terkadang kita perlu mengimplementasikan penghapusan lunak. Sehingga jika kami salah menghapus catatan tertentu, kami dapat dengan mudah mengembalikannya. Itulah mengapa ini penting dan harus ada di aplikasi Laravel kita.
Dalam artikel ini, Anda akan mempelajari implementasi lengkap dengan penghapusan lunak Laravel dan cara mengembalikan catatan yang dihapus dengan contoh.
Langkah 1:Instalasi Laravel
Jika Anda tidak menginstal Laravel 8 di lokal Anda, jalankan perintah berikut di bawah ini:
composer create-project --prefer-dist laravel/laravel laravel-soft-delete
Setelah selesai di atas, kita perlu menginstal Laravel Collective Package, jalankan perintah berikut di bawah ini:
composer require laravelcollective/html
Langkah 2:Konfigurasi Basis Data
Jika proyek Laravel . Anda segar maka Anda perlu memperbarui kredensial basis data Anda. Cukup buka file .env di proyek Laravel 8 Anda.
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here
Langkah 3:Pengaturan Migrasi
Mari buat migrasi untuk proyek **laravel soft delete **contoh. Dalam contoh ini, kami menggunakan tabel pengguna yang migrasinya sudah ada di instalasi Laravel. Jadi kita hanya perlu mengedit migrasi itu. Lihat di bawah kode pembaruan:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->softDeletes();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Seperti yang Anda lihat, kami menambahkan $table->softDeletes(); metode untuk mengimplementasikan penghapusan lunak laravel.
Sekarang mari kita jalankan perintah berikut di bawah ini:
php artisan migrate
Langkah 4:Menyiapkan Rute
Dalam contoh saya, saya akan membuat rute mentah saya secara manual. Cukup buka "routes/web.php" file dan tambahkan rute berikut.
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::group(['namespace' => 'App\Http\Controllers'], function()
{
/**
* Home Routes
*/
Route::get('/', 'HomeController@index')->name('home.index');
Route::group(['prefix' => 'users'], function() {
Route::get('/', 'UsersController@index')->name('users.index');
Route::get('/create', 'UsersController@create')->name('users.create');
Route::post('/create', 'UsersController@store')->name('users.store');
Route::get('/{user}/show', 'UsersController@show')->name('users.show');
Route::get('/{user}/edit', 'UsersController@edit')->name('users.edit');
Route::patch('/{user}/update', 'UsersController@update')->name('users.update');
Route::delete('/{user}/delete', 'UsersController@destroy')->name('users.destroy');
Route::post('/{user}/restore', 'UsersController@restore')->name('users.restore');
Route::delete('/{user}/force-delete', 'UsersController@forceDelete')->name('users.force-delete');
Route::post('/restore-all', 'UsersController@restoreAll')->name('users.restore-all');
});
});
Seperti yang Anda lihat, kami menambahkan restore, force-delete, dan restore-all route. Anda akan melihat kode pengontrol kami untuk rute ini.
Langkah 5:Menyiapkan Model untuk Penghapusan Lunak kami
Seperti yang Anda lihat di bawah, kami mengimpor penggunaan Illuminate\Database\Eloquent\SoftDeletes; kelas dan menggunakannya dalam model Pengguna kami.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, SoftDeletes;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'username',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* Always encrypt password when it is updated.
*
* @param $value
* @return string
*/
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
}
Langkah 6:Laravel Soft Delete &Restore Metode Pengontrol Rekaman yang Dihapus
Metode indeks di dalam UserController.php seperti yang Anda lihat, saya memeriksa apakah ada status dengan nilai yang diarsipkan dari permintaan dan memanggil metode $users->onlyTrashed() sehingga hanya penghapusan lunak yang akan ditampilkan pada daftar.
/**
* Display all users
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$users = User::latest();
if($request->get('status') == 'archived') {
$users = $users->onlyTrashed();
}
$users = $users->paginate(10);
return view('users.index', compact('users'));
}
Dalam metode ini di dalam UserController.php saya memanggil withTrashed() dan pulihkan() metode ini akan memungkinkan kami untuk memulihkan catatan yang dihapus.
/**
* Restore user data
*
* @param User $user
*
* @return \Illuminate\Http\Response
*/
public function restore($id)
{
User::where('id', $id)->withTrashed()->restore();
return redirect()->route('users.index', ['status' => 'archived'])
->withSuccess(__('User restored successfully.'));
}
Ini adalah implementasi paksa untuk menghapus catatan yang dibuang menggunakan forceDelete() metode.
/**
* Force delete user data
*
* @param User $user
*
* @return \Illuminate\Http\Response
*/
public function forceDelete($id)
{
User::where('id', $id)->withTrashed()->forceDelete();
return redirect()->route('users.index', ['status' => 'archived'])
->withSuccess(__('User force deleted successfully.'));
}
Dalam tindakan ini, kami memanggil onlyTrashed() dan pulihkan() metode sehingga kita semua akan mengembalikan catatan yang dibuang.
/**
* Restore all archived users
*
* @param User $user
*
* @return \Illuminate\Http\Response
*/
public function restoreAll()
{
User::onlyTrashed()->restore();
return redirect()->route('users.index')->withSuccess(__('All users restored successfully.'));
}
Langkah 7:Laravel Soft Hapus Pengontrol Pengguna
Di bawah ini adalah kode lengkap untuk UserController.php kami dengan implementasi Laravel 8 soft delete and restore record yang dihapus.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
class UsersController extends Controller
{
/**
* Display all users
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$users = User::latest();
if($request->get('status') == 'archived') {
$users = $users->onlyTrashed();
}
$users = $users->paginate(10);
return view('users.index', compact('users'));
}
/**
* Show form for creating user
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('users.create');
}
/**
* Store a newly created user
*
* @param User $user
* @param StoreUserRequest $request
*
* @return \Illuminate\Http\Response
*/
public function store(User $user, StoreUserRequest $request)
{
//For demo purposes only. When creating user or inviting a user
// you should create a generated random password and email it to the user
$user->create(array_merge($request->validated(), [
'password' => 'test'
]));
return redirect()->route('users.index')
->withSuccess(__('User created successfully.'));
}
/**
* Show user data
*
* @param User $user
*
* @return \Illuminate\Http\Response
*/
public function show(User $user)
{
return view('users.show', [
'user' => $user
]);
}
/**
* Edit user data
*
* @param User $user
*
* @return \Illuminate\Http\Response
*/
public function edit(User $user)
{
return view('users.edit', [
'user' => $user
]);
}
/**
* Update user data
*
* @param User $user
* @param UpdateUserRequest $request
*
* @return \Illuminate\Http\Response
*/
public function update(User $user, UpdateUserRequest $request)
{
$user->update($request->validated());
return redirect()->route('users.index')
->withSuccess(__('User updated successfully.'));
}
/**
* Delete user data
*
* @param User $user
*
* @return \Illuminate\Http\Response
*/
public function destroy(User $user)
{
$user->delete();
return redirect()->route('users.index')
->withSuccess(__('User deleted successfully.'));
}
/**
* Restore user data
*
* @param User $user
*
* @return \Illuminate\Http\Response
*/
public function restore($id)
{
User::where('id', $id)->withTrashed()->restore();
return redirect()->route('users.index', ['status' => 'archived'])
->withSuccess(__('User restored successfully.'));
}
/**
* Force delete user data
*
* @param User $user
*
* @return \Illuminate\Http\Response
*/
public function forceDelete($id)
{
User::where('id', $id)->withTrashed()->forceDelete();
return redirect()->route('users.index', ['status' => 'archived'])
->withSuccess(__('User force deleted successfully.'));
}
/**
* Restore all archived users
*
* @param User $user
*
* @return \Illuminate\Http\Response
*/
public function restoreAll()
{
User::onlyTrashed()->restore();
return redirect()->route('users.index')->withSuccess(__('All users restored successfully.'));
}
}
Langkah 8:Tampilan Blade Indeks
Kode di bawah ini tentang index.blade.php kami yang kami kode implementasi penghapusan lunak Laravel.
@extends('layouts.app-master')
@section('content')
<h1 class="mb-3">Laravel Soft Delete Example - codeanddeploy.com</h1>
<div class="bg-light p-4 rounded">
<h1>Users</h1>
<div class="lead">
Manage your users here.
<a href="{{ route('users.create') }}" class="btn btn-primary btn-sm float-right">Add new user</a>
</div>
<div class="mt-2">
@include('layouts.partials.messages')
<br>
<a href="/users">All users</a> | <a href="/users?status=archived">Archived users</a>
<br><br>
@if(request()->get('status') == 'archived')
{!! Form::open(['method' => 'POST','route' => ['users.restore-all'],'style'=>'display:inline']) !!}
{!! Form::submit('Restore All', ['class' => 'btn btn-primary btn-sm']) !!}
{!! Form::close() !!}
@endif
</div>
<table class="table table-striped">
<thead>
<tr>
<th scope="col" width="1%">#</th>
<th scope="col" width="15%">Name</th>
<th scope="col">Email</th>
<th scope="col" width="10%">Username</th>
<th scope="col" width="1%" colspan="4"></th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<th scope="row">{{ $user->id }}</th>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->username }}</td>
<td><a href="{{ route('users.show', $user->id) }}" class="btn btn-warning btn-sm">Show</a></td>
<td><a href="{{ route('users.edit', $user->id) }}" class="btn btn-info btn-sm">Edit</a></td>
<td>
@if(request()->get('status') == 'archived')
{!! Form::open(['method' => 'POST','route' => ['users.restore', $user->id],'style'=>'display:inline']) !!}
{!! Form::submit('Restore', ['class' => 'btn btn-primary btn-sm']) !!}
{!! Form::close() !!}
@else
{!! Form::open(['method' => 'DELETE','route' => ['users.destroy', $user->id],'style'=>'display:inline']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger btn-sm']) !!}
{!! Form::close() !!}
@endif
</td>
<td>
@if(request()->get('status') == 'archived')
{!! Form::open(['method' => 'DELETE','route' => ['users.force-delete', $user->id],'style'=>'display:inline']) !!}
{!! Form::submit('Force Delete', ['class' => 'btn btn-danger btn-sm']) !!}
{!! Form::close() !!}
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="d-flex">
{!! $users->links() !!}
</div>
</div>
@endsection
Sekarang Anda memiliki implementasi lengkap untuk penghapusan lunak Laravel termasuk memulihkan catatan yang dihapus.
Saya harap tutorial ini dapat membantu Anda. Silakan kunjungi di sini https://codeanddeploy.com/blog/laravel/complete-laravel-8-soft-delete-restore-deleted-records-tutorial jika Anda ingin mengunduh kode ini.
Selamat coding :)