Oprindeligt indsendt @ https://codeanddeploy.com besøg og download prøvekoden:
https://codeanddeploy.com/blog/laravel/complete-laravel-8-soft-delete-restore-deleted-records-tutorial
I dette indlæg vil jeg dele med dig en komplet Laravel 8 blød sletning og gendannelse af slettede poster tutorial. Når vi udvikler CRUD-operationer i Laravel, er vi nogle gange nødt til at implementere bløde sletninger. Så hvis vi forkert slettede den specifikke post, kan vi nemt gendanne dem. Derfor er dette vigtigt og skal eksistere i vores Laravel-applikation.
I denne artikel lærer du et komplet redskab med Laravel soft delete og hvordan du gendanner de slettede poster med eksempel.
Trin 1:Laravel-installation
Hvis du ikke har en Laravel 8-installation i dit lokale, skal du bare køre følgende kommando nedenfor:
composer create-project --prefer-dist laravel/laravel laravel-soft-delete
Når det er gjort ovenfor, skal vi installere Laravel Collective Package, kør følgende kommando nedenfor:
composer require laravelcollective/html
Trin 2:Databasekonfiguration
Hvis dit Laravel-projekt er frisk, skal du opdatere dine databaselegitimationsoplysninger. Bare åbn .env-filen i dit Laravel 8-projekt.
.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
Trin 3:Opsætning af migrering
Lad os oprette en migrering for vores **laravel blød sletning **eksempelprojekt. I dette eksempel bruger vi brugerens tabel, hvor migreringen allerede eksisterer i Laravel-installationen. Så vi skal bare redigere den migration. Se opdateringskoden nedenfor:
<?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');
}
}
Som du kan se, tilføjede vi $table->softDeletes(); metode til at implementere Laravel soft delete.
Lad os nu køre følgende kommando nedenfor:
php artisan migrate
Trin 4:Opsætning af ruter
I mit eksempel vil jeg manuelt oprette mine crud-ruter. Bare åbn "routes/web.php" fil og tilføj følgende ruter.
<?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');
});
});
Som du kan se, tilføjede vi gendannelse, tvungen sletning og gendan-alle ruter. Du vil se vores controller-kode for disse ruter.
Trin 5:Opsætning af model for vores bløde sletning
Som du kan se nedenfor importerede vi brugen Illuminate\Database\Eloquent\SoftDeletes; klasse og bruge den i vores brugermodel.
<?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);
}
}
Trin 6:Laravel Soft Slet &Gendan slettede Records Controller-metoder
Indeksmetode inde i UserController.php, som du kan se, har jeg tjekket om der er en status med den arkiverede værdi fra anmodningen og kalder metoden $users->onlyTrashed() så kun soft deleted vil blive vist på listerne.
/**
* 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'));
}
I denne metode inde i UserController.php kaldte jeg withTrashed() og gendan() metoder dette vil give os mulighed for at gendanne den slettede post.
/**
* 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.'));
}
Dette er implementeringen af tvunget til at slette posten i papirkurven ved hjælp af 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.'));
}
I denne handling kaldte vi onlyTrashed() og gendan() metoder, så vi alle vil gendanne de optegnelser, der er smadret.
/**
* 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.'));
}
Trin 7:Laravel Soft Delete User Controller
Nedenfor er den komplette kode til vores UserController.php med implementeringer af Laravel 8 blød sletning og gendannelse af slettede poster.
<?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.'));
}
}
Trin 8:Indeksbladsvisning
Kode nedenfor om vores index.blade.php, som vi koder Laravel soft delete implementeringerne.
@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 har du de komplette implementeringer til Laravel soft delete, inklusive gendannelse af slettede poster.
Jeg håber, at denne tutorial kan hjælpe dig. Besøg venligst her https://codeanddeploy.com/blog/laravel/complete-laravel-8-soft-delete-restore-deleted-records-tutorial, hvis du vil downloade denne kode.
God kodning :)