Detailed below are different methods to delete records from database using Laravel Eloquent ORM. It provides easy and efficient way to delete data.
1. Deleting a single record:
delete()
method using:delete()
method.
<code class="language-php">use App\Models\Post; // রেকর্ড খুঁজে বের করুন $post = Post::find(1); // রেকর্ড মুছে ফেলুন $post->delete();</code>
Remember: After deletion, the record will no longer be in the database.
2. Deleting multiple records:
Using thewhere
delete()
clause:To delete multiple records, use the where
method with the delete()
clause.
<code class="language-php">use App\Models\Post; // 'draft' স্ট্যাটাসের সকল রেকর্ড মুছে ফেলুন Post::where('status', 'draft')->delete();</code>
3. Using the destroy()
method:
destroy()
method.
<code class="language-php">use App\Models\Post; // একক রেকর্ড মুছে ফেলুন Post::destroy(1); // একাধিক রেকর্ড মুছে ফেলুন Post::destroy([2, 3, 4]);</code>
Remember: The destroy()
method directly deletes records using the primary key.
4. Using model event:
Model Events are triggered when Eloquent models are deleted.
deleting
deleted
<code class="language-php">class Post extends Model { protected static function booted() { static::deleting(function ($post) { // মুছে ফেলার আগে করণীয় কাজ Log::info('Post is being deleted: ' . $post->id); }); static::deleted(function ($post) { // মুছে ফেলার পর করণীয় কাজ Log::info('Post deleted: ' . $post->id); }); } }</code>
5. Soft Deletes:
What is soft delete? column.deleted_at
trait must be added to the SoftDeletes
model.
<code class="language-php">use App\Models\Post; // রেকর্ড খুঁজে বের করুন $post = Post::find(1); // রেকর্ড মুছে ফেলুন $post->delete();</code>
<code class="language-php">use App\Models\Post; // 'draft' স্ট্যাটাসের সকল রেকর্ড মুছে ফেলুন Post::where('status', 'draft')->delete();</code>
<code class="language-php">use App\Models\Post; // একক রেকর্ড মুছে ফেলুন Post::destroy(1); // একাধিক রেকর্ড মুছে ফেলুন Post::destroy([2, 3, 4]);</code>
<code class="language-php">class Post extends Model { protected static function booted() { static::deleting(function ($post) { // মুছে ফেলার আগে করণীয় কাজ Log::info('Post is being deleted: ' . $post->id); }); static::deleted(function ($post) { // মুছে ফেলার পর করণীয় কাজ Log::info('Post deleted: ' . $post->id); }); } }</code>
withTrashed()
: Returns both soft deleted and non-deleted records.onlyTrashed()
: will restore only soft deleted records.6. Direct deletion from database:
Records can be deleted directly with SQL queries using Laravel's DB
facade.
<code class="language-php">use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use SoftDeletes; protected $dates = ['deleted_at']; }</code>
The above is the detailed content of Laravel Eloquent ORM in Bangla Part-Deleting Models). For more information, please follow other related articles on the PHP Chinese website!