purushetty's avatar

Chaining "truncate()" and "insert()" together within the same builder query

Has anyone tried this before? I am currently using Laravel 10 and trying to chain truncate and insert together within the same statement. It doesn't work and throws up an error but works fine when I split them.

Does not work DB::table($valueArr['table'])->truncate()->insert($valueArr['data']);

Works DB::table($valueArr['table'])->truncate(); DB::table($valueArr['table'])->insert($valueArr['data']);

Error "Call to a member function insert() on null"

Am I missing something here?

0 likes
3 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@purushetty The truncate() returns null, not the query builder instance. So chaining insert() after truncate() causes the error: "Call to a member function insert() on null".

So, always call truncate() and insert() in separate statements:

DB::table($table)->truncate();
DB::table($table)->insert($data);

You cannot chain truncate() with other methods like insert().

Snapey's avatar

query builder constructs a query, but certain methods terminate the query and run it.

  • find()
  • first()
  • get()
  • paginate()

to name a few. truncate() is one of these.

Please or to participate in this conversation.