Search code examples
phplaraveleloquentlaravel-query-builder

Laravel: Convert QueryBuilder to Eloquent:ORM


How to return, with eloquent, all files where column deleted_at is null. I can access the value of deleted_at like this $media->model['deleted_at']

In controller I return $files to the view.

$files = $media->paginate(3);

In my view, code below give me empty <iframe> if file is deleted.

@foreach ($files as $media)
    @if(is_null($media->model['deleted_at']))
       @php($id = $media->model['id'])
       @php($file_name = $media->model['document_file'][0]['file_name'])
       <iframe style="width: 500px; height: 700px;" src="{{ asset("storage/$id/$file_name") }}"></iframe>
    @endif
@endforeach

With QueryBuilder I can do it like this, but how can make the same with eloquent.

$file = DB::table('media')
    ->join('files', 'media.model_id', '=', 'files.id')
    ->select('model_id', 'file_name')
    ->where('deleted_at', '=',null)
    ->paginate(3);

Solution

  • Laravel has a Scout package that has a withTrashed() function to retrieve none deleted and soft deleted if you only want the trashed you could use the onlyTrashed() function.

    $files = Media::has('files')->withTrashed()->get();
    

    Source: Laravel Soft delete