Create a Insert... Select statement in Laravel
There is no way of doing this in one query (unless you are on Laravel 5.7), however I came across the same issue and wanted to make sure I can keep using a certain select I build with the QueryBuilder.
So what you could do, to keep things half what clean and to reuse functionality which has built a select statement before, is this:
/**
* Wherever your Select may come from
**/
$select = User::where(...)
->where(...)
->whereIn(...)
->select(array('email','moneyOwing'));
/**
* get the binding parameters
**/
$bindings = $select->getBindings();
/**
* now go down to the "Network Layer"
* and do a hard coded select
*/
$insertQuery = 'INSERT into user_debt_collection (email,dinero) '
. $select->toSql();
\DB::insert($insertQuery, $bindings);
UPDATE Laravel 5.7
As of Laravel 5.7.17 you can use ->insertUsing(). See here for details. Thank you @Soulriser for pointing this out.
So above query would look like this:
DB::table('user_debt_collection')->insertUsing(['email','dinero'], $select);
You can use:
DB::insert("insert into contacts(contact_id,contact_type,account_id,created_at,updated_at) select f.id,'App\\Friend',f.account_id,f.created_at,f.updated_at from friends as f where f.id=?",[16]);
I used DB::statement("...");
DB::statement("INSERT INTO table (SELECT)");