仅获取软删除的记录

时间:2017-01-05 11:43:29

标签: php laravel api laravel-5.3

我创建了一种方法来仅获取LessonsController中的软删除课程

我没有得到应该是我的课程控制器的路线

<?php

namespace App\Http\Controllers;

use Response;
use App\lesson;
use Illuminate\Http\Request;
use App\Acme\Transformers\LessonTransformer;
use Illuminate\Support\Facades\Input;

class LessonsController extends ApiController 
{

    protected $lessonTransformer;

    function __construct(LessonTransformer $lessonTransformer) 
    {
        $this->lessonTransformer = $lessonTransformer;
    }

    //fetch all and pass a metadata 'data' 
    public function index() 
    {
        $lessons = Lesson::all();

        return $this->respond([
            'data' => $this->lessonTransformer->transformCollection($lessons->all())
        ]);
    }

    //delete a lesson by id
    public function destroy($id)
    {   
        $dlesson = Lesson::find(input::get('id'));

        if(! $dlesson) {
            return $this->respondNotFound();
        }

        $dlesson->delete();

        return $this->respondDeleted('Lesson deleted successfully');
    }

    public function deletedLessons() 
    {
        $deleted_lessons = Lesson::onlyTrashed()->get();

        return $this->respond([
            'data' => $this->lessonTransformer->transformCollection($lessons->all())
        ]);
    }    

}

我尝试过删除过的记录 http://localhost:8000/api/v1/lessons/11

谢谢

1 个答案:

答案 0 :(得分:1)

确保:

  • 您在迁移中使用了softDeletes()方法并执行了此迁移
  • 您在模型中使用SoftDeletes特征
  • 您已在模型
  • 中将deleted_at添加到$dates属性

https://laravel.com/docs/5.3/eloquent#soft-deleting

完成所有操作后,您的查询将正常工作,并且只返回软删除的课程:

$deleted_lessons = Lesson::onlyTrashed()->get();