1

I would like to start using soft delete models with the query builder of Laravel

By the way, I created the column deleted_at and I implemented soft delete models in the model.

Request.php:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request as Req;
use Illuminate\Database\Eloquent\SoftDeletes;

class Request extends Model
{
    use SoftDeletes;
}

RequestController function:

public function already_deleted_checker($id_req)
    {
        $request_customer_match_rip = DB::table('requests')->onlyTrashed()->select('id')->where('id', '=', $id_req)->get();

        $request_customer_match_rip_len = count($request_customer_match_rip);

        if ($request_customer_match_rip_len > 0) {
            return true;
        } 
    }

The function already_deleted_checker should check if the value in the deleted_at column is null or not... but unfortunately when I run the function I visualize the following error in the browser:

Call to undefined method Illuminate\Database\Query\Builder::onlyTrashed()

Can help?

1
  • 1
    Just a tip... avoid giving class names like: Model, Request, Controller because those already exist and sometimes it can bring only trouble! Commented May 20, 2020 at 7:57

2 Answers 2

2

Why would you use DB instead of Eloquent Models ?

Simply :

 App\Request::onlyTrashed()->select('id')->where('id', '=', $id_req)->get();

DB facade doesn't know onlyTrashed() method.

Sign up to request clarification or add additional context in comments.

Comments

1

When using soft deletes, you should use the Model QueryBuilder instead of the generic one, actual in general you should 99% of the time use the Model QueryBuilder.

Request::onlyTrashed()->select('id')->where('id', $id_req)->get();

2 Comments

With your code it works however the value in the column "deleted_at" remains null when I delete a row... is it normal? I understood that the value should become the current timestamp.
you should also delete it as a model, Request::find($id)->delete();, looking at your initial code, i would assume you would use the DB::facade there too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.