Laravel 5.2 soft delete does not work

筅森魡賤 提交于 2020-02-06 04:15:43

问题


I am have simple app with a table post and model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use SoftDeletes;
class Post extends Model
{
   protected $table = 'post';

   protected $dates = ['deleted_at'];

   protected $softDelete = true;

}

I am trying to make example of soft delete and i am using route just for example route.php:

<?php
use App\Post;

use Illuminate\Database\Eloquent\SoftDeletes;
Route::get('/delete', function(){
    $post = new Post();
    Post::find(12)->delete();

});

I have a column "created_at" created with migration:

    Schema::table('post', function (Blueprint $table) {
        $table->softDeletes();
    });

, but instead of adding time to this column, when I run the site it deletes the row with selected id. Where am I wrong ?


回答1:


You need to use SoftDeletes trait inside your model like so:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
   use SoftDeletes;

   protected $table = 'post';

   protected $dates = ['deleted_at'];
}

Now you, are not applying trait, so obviously it doesn't work.

In addition you have unnecessary piece of code in your routes file. It should look like this:

<?php
use App\Post;

Route::get('/delete', function(){
    Post::find(12)->delete();
});


来源:https://stackoverflow.com/questions/38518175/laravel-5-2-soft-delete-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!