php - Problem with restoring deleted notification in Laravel

I am trying to restore deleted notification using Laravel Notification. Problem I am having is that I get error

Call to undefined method Illuminate\\Notifications\\Notification::withTrashed()

because Notification model is in vendor folder and I can't change it. So I need some workaround for that in order for withTrashed method to be available in Notification model. Any help is appreciated. Here is my code.

Controller

public function restoreDeletedNotification(Request $request)
{
    $restore = Notification::withTrashed()->where('id', $request['id'])->restore();

    return response()->noContent();
}

web.php

Route::post('/notifications/restore', [\App\Http\Controllers\NotificationController::class, 'restoreDeletedNotification'])->name('restore-notification');

Answer

Solution:

First note that:

  • By default Laravel Notification's migration file doesn't have a deleted_at.
  • You are calling Illuminate\\Notifications\\Notification which doesn't extend Model class so there is no withTrashed() method.

Solution:

What we are going to do is a workaround. You need to create a Notification model (in your app directory or app/Models if you are using Laravel 8) which extends Model then you will use SoftDeletes trait.

class Notification extends Model
{
    use SoftDeletes;

     /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
}

Now you need to create a migration file to add deleted_at column in your notification table like so

  1. run php artisan make:migration AddDeletedAtColumnToNotificationsTable
  2. in the migration file you will add
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('notifications', function (Blueprint $table) {
        $table->softDeletes()->after('updated_at');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('notifications', function (Blueprint $table) {
        $table->dropColumn('deleted_at');
    });
}
  1. run php artisan migrate

Now you can use App\Notification::withTrashed()->where('id', $request['id'])->restore();.

Source