Oorspronkelijk gepost @ https://codeanddeploy.com bezoek en download de voorbeeldcode:
https://codeanddeploy.com/blog/laravel/complete-laravel-8-soft-delete-restore-deleted-records-tutorial
In dit bericht zal ik een complete Laravel 8 soft delete en restore verwijderde records met je delen zelfstudie. Bij het ontwikkelen van CRUD-bewerkingen in Laravel moeten we soms zachte verwijderingen implementeren. Zodat als we het specifieke record onjuist hebben verwijderd, we ze gemakkelijk kunnen herstellen. Daarom is dit belangrijk en moet het aanwezig zijn in onze Laravel-applicatie.
In dit artikel leert u een compleet werktuig met Laravel soft delete en hoe u de verwijderde records kunt herstellen met een voorbeeld.
Stap 1:Laravel-installatie
Als u geen Laravel 8-installatie in uw lokaal hebt, voert u gewoon de volgende opdracht hieronder uit:
composer create-project --prefer-dist laravel/laravel laravel-soft-delete
Eenmaal hierboven gedaan, moeten we het Laravel Collective Package, . installeren voer de volgende opdracht hieronder uit:
composer require laravelcollective/html
Stap 2:Databaseconfiguratie
Als uw Laravel-project vers is, moet u uw databasegegevens bijwerken. Open gewoon het .env-bestand in uw Laravel 8-project.
.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
Stap 3:Migratie instellen
Laten we een migratie maken voor ons **laravel soft delete **voorbeeldproject. In dit voorbeeld gebruiken we de gebruikerstabel waarvan de migratie al bestaat in de Laravel-installatie. Dus we hoeven alleen die migratie te bewerken. Zie onderstaande updatecode:
<?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');
}
}
Zoals je kunt zien hebben we de $table->softDeletes(); . toegevoegd methode om de laravel soft delete te implementeren.
Laten we nu de volgende opdracht hieronder uitvoeren:
php artisan migrate
Stap 4:Routes instellen
In mijn voorbeeld zal ik handmatig mijn ruwe routes maken. Open gewoon de "routes/web.php" bestand en voeg de volgende routes toe.
<?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');
});
});
Zoals je kunt zien, hebben we herstel-, geforceerd-verwijderen en herstel-alle routes toegevoegd. U ziet onze controllercode voor deze routes.
Stap 5:Model instellen voor onze Soft delete
Zoals je hieronder kunt zien, hebben we het gebruik Illuminate\Database\Eloquent\SoftDeletes geïmporteerd; class en gebruik het in ons gebruikersmodel.
<?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);
}
}
Stap 6:Laravel Soft Delete &Restore verwijderde records Controller-methoden
Indexmethode binnen UserController.php zoals je kunt zien, heb ik gecontroleerd of er een status is met de gearchiveerde waarde van het verzoek en roep de methode $users->onlyTrashed() aan zodat alleen zacht verwijderd wordt weergegeven in de lijsten.
/**
* 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'));
}
In deze methode binnen UserController.php heb ik de withTrashed() . aangeroepen en restore() methoden zullen dit ons in staat stellen om het verwijderde record te herstellen.
/**
* 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.'));
}
Dit is de implementatie van het gedwongen verwijderen van het verwijderde record met behulp van forceDelete() methode.
/**
* 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.'));
}
In deze actie noemden we de onlyTrashed() en restore() methoden, zodat we allemaal de records herstellen die in de prullenbak zijn terechtgekomen.
/**
* 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.'));
}
Stap 7:Laravel Soft Delete gebruikerscontroller
Hieronder vindt u de volledige code voor onze UserController.php met implementaties van Laravel 8 soft delete en restore verwijderde records.
<?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.'));
}
}
Stap 8:Indexbladweergave
Code hieronder over onze index.blade.php waarmee we de Laravel soft delete-implementaties coderen.
@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
Nu heb je de volledige implementaties voor Laravel soft delete inclusief het herstellen van verwijderde records.
Ik hoop dat deze tutorial je kan helpen. Bezoek hier https://codeanddeploy.com/blog/laravel/complete-laravel-8-soft-delete-restore-deleted-records-tutorial als je deze code wilt downloaden.
Veel plezier met coderen :)