Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

mysql - Query builder don't accept onlyTrashed()

I'm a beginner and cant find a solution to my problem. I trying to get "onlyTrashed" from my DB but Laravel 8 don't accept my query commands :( I tried many scenarios but unsuccessful.

namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesDB;
use AppModelsCategory;

class CategoryController extends Controller{   
 public function AllCat(){

        $categories = $trashCat = DB::table('categories')
            ->join('users','categories.user_id','users.id')
            ->select('categories.*','users.name')
            ->latest()
            ->paginate(5);
          
           //$categories = Category::latest()->paginate(5);
          // $trashCat = Category::onlyTrashed()->latest()->paginate(3);
            
        return view('admin.category.index', compact('trashCat','categories'));

public function SoftDelete($id){
     $delete = Category::find($id);`enter code here`
     return Redirect()->back()->wiht('success',' Category Delete Successfuly');

Route::get('/softdelete/category/{id}', [CategoryController::class,'SoftDelete']);
question from:https://stackoverflow.com/questions/65928805/query-builder-dont-accept-onlytrashed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Please make sure that your model imports and uses SoftDeletes trait to implement soft delete in your model and make sure that your table has deleted_at field, your model may look like below codes.

<?php

namespace AppModels;

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;

class Category extends Model
{
    use SoftDeletes;

And in your SoftDelete function within the controller, I think you miss delete() function, your function should look like:

public function SoftDelete($id) {
    $delete = Category::find($id)->delete();
    return redirect()->back()->with('success',' Category Delete Successfully');
}

Once you implement SoftDeletes trait into your model, delete() function should mark deleted by filling the deleted_at with timestamp or DateTime automatically. Once you implement the above codes, onlyTrashed() should work.

$categories = Category::latest()->paginate(5);
$trashCat = Category::onlyTrashed()->latest()->paginate(3);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...